2012-11-27 14 views
0

我正在自定義一個UIView。-drawRect,RoundCorner,Shadow不能一起工作

要求: 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和圖層,任何建議或建議的參考有一些錯誤的概念或混淆?

回答

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


}