-drawRect,RoundCorner,Shadow无法一起工作

时间:2012-11-27 09:39:37

标签: objective-c core-graphics calayer

我正在定制一个UIView。

要求: 1.纹理背景 圆角。 3.投下阴影。

我已经在

中完成了
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();

//draw the background texture
UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mainBG"]];
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);

//cover it with a desired Color
UIColor *startColor = [UIColor colorWithRed:50/255.f green:50/255.f blue:50/255.f alpha:0.55f];

UIColor *endColor = [UIColor colorWithRed:40/255.f green:40/255.f blue:40/255.f alpha:0.55f];

drawLinearGradient(context, rect, startColor.CGColor, endColor.CGColor);

//make round corner

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                               byRoundingCorners:UIRectCornerAllCorners                                                       cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;

//make shadow

self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOpacity = 0.3f;
self.layer.shadowOffset = CGSizeMake(3.0f, 3.0f);
self.layer.shadowRadius = 5.0f;
self.layer.shadowPath = maskPath.CGPath;

}

此代码符合前两个,但第三个没有。

似乎我对如何使用CoreGraphics和Layer,任何建议或建议参考有一些错误的概念或困惑?

1 个答案:

答案 0 :(得分:0)

您应首先创建圆角路径,然后绘制到它。

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGPathRef roundPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10.0f].CGPath;
    CGContextAddPath(context, roundPath);
    CGContextClip(context);
    //continue drawing here

    //draw the background texture
    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mainBG"]];
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    //cover it with a desired Color
    UIColor *startColor = [UIColor colorWithRed:50/255.f green:50/255.f blue:50/255.f alpha:0.55f];

    UIColor *endColor = [UIColor colorWithRed:40/255.f green:40/255.f blue:40/255.f alpha:0.55f];
    drawLinearGradient(context, rect, startColor.CGColor, endColor.CGColor);

    //draw the shadow    
    UIColor *shadowColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f];
    CGContextSetShadowWithColor(context, CGSizeMake(3.0f, 3.0f), 5.0f, [shadowColor CGColor]);
    CGContextEOFillPath(context);


}