0

我正在定制一个 UIView。

要求:1.纹理背景2.圆角。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 有一些错误的概念或困惑,有什么建议或建议的参考吗?

4

1 回答 1

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);


}
于 2012-11-27T09:57:09.697 回答