将阴影放置到矩形中(drawRect:(CGRect)rect) [英] Put shadow to a rectangle (drawRect:(CGRect)rect)

查看:180
本文介绍了将阴影放置到矩形中(drawRect:(CGRect)rect)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I did a rectangle with this code and it works:

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

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

But now i want to put a shadow, I tried with this:

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

但是xcode告诉我有关 NSMakeSize的信息:向不兼容的参数发送'int'输入'CGSize'

But xcode tell me about NSMakeSize : Sending 'int' to parameter of incompatible type 'CGSize'

关于阴影的正确形式是什么?
谢谢!

Which is the correct form about shadows? Thanks!!

推荐答案

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

You should invoke CGContextSetShadow(...) function before the functions that draw object that should have a shadow. Here is the complete code:

- (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)); 提供了一些随机值。您应该只在通过 rect 参数接收的矩形内绘制。

I have noticed that you provide some random values to CGContextAddRect(context, CGRectMake(60, 60, 100, 1));. You should draw only within the rectangle that you receive through rect parameter.

这篇关于将阴影放置到矩形中(drawRect:(CGRect)rect)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆