Mrw*_*lfy 3 core-graphics drawrect ios
使用下面的代码,我绘制一个圆角矩形.它绘制了一个漂亮的浅灰色填充圆角矩形(大小为"self").我实际上想绘制这个像素的倒数,即:不是一个实心的圆角矩形,而是一个实心的浅灰色矩形中这个圆形矩形形状的窗口或孔.
我需要使用反向剪辑方法吗?或者我需要使用bezier路径?借口如果这是非常基本的,虽然找不到信息.
谢谢阅读!
- (void)drawRect:(CGRect)rect
{
// get the context
CGContextRef context = UIGraphicsGetCurrentContext
CGContextSaveGState(context);
//draw the rounded rectangle
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextSetRGBFillColor(context, 0.8, 0.8, 0.8, 1.0);
CGContextSetLineWidth(context, _lineWidth);
CGRect rrect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect), CGRectGetHeight(rect));
CGFloat radius = _cornerRadius;
CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
CGContextMoveToPoint(context, minx, midy);
// Add an arc through 2 to 3
CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
// Add an arc through 4 to 5
CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
// Add an arc through 6 to 7
CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
// Add an arc through 8 to 9
CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
// Close the path
CGContextClosePath(context);
// Fill the path
CGContextDrawPath(context, kCGPathFill);
CGContextRestoreGState(context);
}
Run Code Online (Sandbox Code Playgroud)
mat*_*att 11
这是另一种方法,只使用UI对象调用:
- (void)drawRect:(CGRect)rect
{
[[UIColor lightGrayColor] setFill];
CGRect r2 = CGRectInset(rect, 10, 10);
UIBezierPath* p = [UIBezierPath bezierPathWithRoundedRect:r2 cornerRadius:15];
[p appendPath: [UIBezierPath bezierPathWithRect:rect]];
p.usesEvenOddFillRule = YES;
[p fill];
}
Run Code Online (Sandbox Code Playgroud)
收益率:

白色是窗户的背景; 灰色是UIView.正如你所看到的,我们正在通过视图看到它背后的任何东西,听起来就像你所描述的那样.