将阴影添加到圆形视图

时间:2013-01-11 04:20:46

标签: objective-c uiview

我正在尝试在圆形视图后面添加一个阴影,但是我的尝试让我只看到了我视图边框上的阴影 - 这个阴影也没有一直出现在视图周围(只是顶部) 。这是我的代码:

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

}

感谢阅读。

2 个答案:

答案 0 :(得分:2)

我认为你正在削减阴影。尝试使剪切路径矩形稍大或椭圆矩形稍小。

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

答案 1 :(得分: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];


}