2013-01-11 211 views
2

我想在圓形視圖後面添加陰影,但我的嘗試導致我在視圖的邊框上僅顯示一個陰影,並且此陰影不會在視圖周圍出現(只是頂部)。這裏是我的代碼:將陰影添加到圓形視圖

-(void)drawRect:(CGRect)dirtyRect{ 
    CGContextRef ctx=UIGraphicsGetCurrentContext(); 
    CGRect bounds=[self bounds]; 

    // Figure out the centre of the bounds rectangle 
    CGPoint centre; 
    centre.x=bounds.origin.x+0.5*bounds.size.width; 
    centre.y=bounds.origin.y+0.5*bounds.size.height; 

    // Clip context 
    CGPathRef path = CGPathCreateWithEllipseInRect(bounds, NULL); 
    CGContextAddPath(ctx, path); 
    CGContextClip(ctx); 

    // Add black outline 
    path = CGPathCreateWithEllipseInRect(bounds, NULL); 
    CGContextAddPath(ctx, path); 
    [[UIColor blackColor] setStroke]; 
    CGContextSetLineWidth(ctx, 3.0); 

    // Specify shadow 
    CGSize offset=CGSizeMake(1,4); 
    CGColorRef colour=[[UIColor darkGrayColor] CGColor]; 
    CGContextSetShadowWithColor(ctx, offset, 2, colour); 

    // Draw image 
    UIImage *littleImage=[UIImage imageNamed:@"image.png"]; 
    [littleImage drawInRect:bounds]; 

    CGContextStrokePath(ctx); 

} 

感謝您的閱讀。

回答

1

好的,有一些事情需要做,以解決這個問題。我認爲這個代碼可能會減少幾行,但這是什麼工作:

-(void)drawRect:(CGRect)dirtyRect{ 
    CGContextRef ctx=UIGraphicsGetCurrentContext(); 

    // Create bounds and path for rectangle slightly smaller than view (Thanks, Andrew T., for this!) 
    CGRect bounds=[self bounds]; 
    CGFloat smallerBy=20.0; 
    CGRect smallBounds=CGRectMake(bounds.origin.x+smallerBy/2, bounds.origin.y+smallerBy/2, bounds.size.width-smallerBy, bounds.size.height-smallerBy); 
    CGPathRef path = CGPathCreateWithEllipseInRect(smallBounds, NULL); 
    CGContextAddPath(ctx, path); 

    // Add black outline with shadow to bounds 
    [[UIColor blackColor] setStroke]; 
    CGContextSetLineWidth(ctx, 5.0); 
    CGSize offset=CGSizeMake(3,4); 
    CGColorRef colour=[[UIColor lightGrayColor] CGColor]; 
    CGContextSetShadowWithColor(ctx, offset, 8, colour); 
    CGContextStrokePath(ctx); 

    // Draw opaque white circle (to cover up shadow that was leaking "inside" image) 
    [[UIColor whiteColor] setFill]; 
    CGContextSetLineWidth(ctx, 0.0); 
    CGContextFillEllipseInRect(ctx, smallBounds); 

    // Draw shadowless black outline over white circle (the circle had bitten into the original outline) 
    CGContextSetShadowWithColor(ctx, offset, 3, NULL); 
    CGContextAddPath(ctx, path); 
    [[UIColor blackColor] setStroke]; 
    CGContextSetLineWidth(ctx, 5.0); 
    CGContextStrokePath(ctx); 

    // Clip context to bounds 
    CGContextAddPath(ctx, path); 
    CGContextClip(ctx); 

    // Draw image 
    UIImage *newImage=[UIImage imageNamed:@"image.png"]; 
    [newImage drawInRect:smallBounds]; 


} 
2

我認爲你正在剪影。嘗試使裁剪路徑的直徑稍大或橢圓直徑稍小一些。

您可以通過關閉剪輯並查看是否出現陰影來測試此功能。

+0

感謝您的答覆。這可以解釋爲什麼陰影不會四處走動,但是陰影出現在視圖內部的問題(就像視圖是透明的並且顯示背後的陰影)仍然會存在......對此有任何想法? – Rogare

+0

我認爲它的行爲正確,因爲你沒有填充橢圓。它顯示線條的陰影。如果用純色填充路徑,則不會看到它。 –