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

}

谢谢阅读。

4

2 回答 2

2

我认为你正在剪裁阴影。尝试使剪切路径矩形大一点或椭圆矩形小一点。

您可以通过关闭剪辑来测试这一点,看看是否出现阴影。

于 2013-01-11T08:52:41.017 回答
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];


}
于 2013-01-16T20:00:42.957 回答