繁体   English   中英

将阴影放置到矩形中(drawRect:(CGRect)rect)

[英]Put shadow to a rectangle (drawRect:(CGRect)rect)

我用此代码制作了一个矩形,它可以正常工作:

- (void)drawRect:(CGRect)rect{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddRect(context, CGRectMake(60, 60, 100, 1));
    CGContextStrokePath(context);
}

但是现在我想放一个阴影,我尝试了一下:

NSShadow* theShadow = [[NSShadow alloc] init];
[theShadow setShadowOffset:NSMakeSize(10.0, -10.0)];
[theShadow setShadowBlurRadius:4.0];

但是xcode告诉我有关NSMakeSize : Sending 'int' to parameter of incompatible type 'CGSize'

关于阴影的正确形式是哪种? 谢谢!!

您应该在绘制应该具有阴影的对象的函数之前调用CGContextSetShadow(...)函数。 这是完整的代码:

- (void)drawRect:(CGRect)rect {
    // define constants
    const CGFloat shadowBlur = 5.0f;
    const CGSize shadowOffset = CGSizeMake(10.0f, 10.0f);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);

    // Setup shadow parameters. Everithyng you draw after this line will be with shadow
    // To turn shadow off invoke CGContextSetShadowWithColor(...) with NULL for CGColorRef parameter.
    CGContextSetShadow(context, shadowOffset, shadowBlur);

    CGRect rectForShadow = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width - shadowOffset.width - shadowBlur, rect.size.height - shadowOffset.height - shadowBlur);
    CGContextAddRect(context, rectForShadow);
    CGContextStrokePath(context);
}

备注:

我注意到您为CGContextAddRect(context, CGRectMake(60, 60, 100, 1));提供了一些随机值CGContextAddRect(context, CGRectMake(60, 60, 100, 1)); 您应该只在通过rect参数收到的矩形内绘制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM