将阴影添加到圆形视图

问题描述:

我想在圆形视图后面添加阴影,但我的尝试导致我在视图的边框上仅显示一个阴影,并且此阴影不会在视图周围出现(只是顶部)。这里是我的代码:将阴影添加到圆形视图

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

} 

感谢您的阅读。

好的,有一些事情需要做,以解决这个问题。我认为这个代码可能会减少几行,但这是什么工作:

-(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]; 


} 

我认为你正在剪影。尝试使裁剪路径的直径稍大或椭圆直径稍小一些。

您可以通过关闭剪辑并查看是否出现阴影来测试此功能。

+0

感谢您的答复。这可以解释为什么阴影不会四处走动,但是阴影出现在视图内部的问题(就像视图是透明的并且显示背后的阴影)仍然会存在......对此有任何想法? – Rogare

+0

我认为它的行为正确,因为你没有填充椭圆。它显示线条的阴影。如果用纯色填充路径,则不会看到它。 –