您可以使用剪切路径来做到这一点。EO 的东西对于定义绘制所有内容的外部空间和不绘制任何内容的内部空间是必要的。
我把这个稍微复杂了一点,因为之后我会放入一个浅色的红色圆圈。
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx); // store to ignore the clipping path later
float margin = self.bounds.size.width * .1;
CGRect ellipseRect = CGRectMake(margin, margin, self.bounds.size.width - 2*margin, self.bounds.size.height - 2*margin);
// OUTER path is just the bounds
CGMutablePathRef mutablePath = CGPathCreateMutable();
CGPathRef pathRef = CGPathCreateWithRect(self.bounds, NULL);
CGPathAddPath(mutablePath, NULL, pathRef);
// INNER path is the same as the ellipse
CGPathRef pathRef2 = CGPathCreateWithEllipseInRect(ellipseRect, NULL);
CGPathAddPath(mutablePath, NULL, pathRef2);
CGContextAddPath(ctx, mutablePath);
CGContextEOClip(ctx);
CGContextSetFillColorWithColor(ctx, UIColor.greenColor.CGColor);
CGContextSetShadowWithColor(ctx, CGSizeMake(margin/2.0f, margin/2.0f), 10, UIColor.blackColor.CGColor);
CGContextFillEllipseInRect(ctx, ellipseRect);
// replace the green circle for a very transparent red one just for fun
CGContextRestoreGState(ctx);
CGContextSetFillColorWithColor(ctx, [UIColor.redColor colorWithAlphaComponent:.1].CGColor);
CGContextSetShadowWithColor(ctx, CGSizeZero, 0, NULL);
CGContextFillEllipseInRect(ctx, ellipseRect);
}