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

OK、これを修正するためにやらなければならないことがいくつかありました。このコードはおそらく数行削減できると思いますが、うまくいったのは次のとおりです。

-(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 に答える