我正在尝试绘制一个半透明的黑色矩形,并从中心切出一个三角形。
我用下面的代码完美地工作。但是,我想圆角三角形的角。
我尝试了几种不同的技术来添加圆角,例如将 CGContextSetLineCap 设置为笔画,并使用 quartz 创建路径并使用 CGContextAddArcToPoint,但我没有得到任何工作。
正如我所提到的,下面的代码适用于三角形切口。我怎样才能使三角形的角变圆?
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint position = CGPointMake(rect.size.width/2, rect.size.height * .7);
CGSize size = CGSizeMake(rect.size.width*.8, rect.size.height*.5);
CGFloat firstPointX = (position.x - (size.width / 2));
CGFloat firstPointY = (position.y - (size.height));
CGPoint firstPoint = CGPointMake(firstPointX, firstPointY);
CGFloat secondPointX = position.x + (size.width / 2);
CGFloat secondPointY = position.y - (size.height);
CGPoint secondPoint = CGPointMake(secondPointX, secondPointY);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
[path addLineToPoint:firstPoint];
[path moveToPoint:firstPoint];
[path addLineToPoint:secondPoint];
[path addLineToPoint:position];
[path closePath];
CGContextAddRect(context, rect);
CGContextAddPath(context, path.CGPath);
CGContextEOClip(context);
UIColor *translucentColor = [UIColor colorWithWhite:0 alpha:0.5];
CGContextSetFillColorWithColor(context, translucentColor.CGColor);
CGContextFillRect(context, rect);
UIGraphicsEndImageContext();
编辑:这是我想要完成的一个例子。
最佳答案
我想你想使用 CGContextAddArc。如有必要,它会绘制一个圆圈的一部分,并带有一条通往它的线。这是绘制填充 UIView 的圆角框的代码。对于三角形,您将有 3 条线而不是 4 条。顶部有两条,底部中间有一条。这是来自我拥有的一个 roundBoxView 类:
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect boxRect = self.bounds;
float bRadius = self.cornerRadius;
float shrink = self.strokeThickness/2;
CGContextBeginPath(context);
// instead of this gray you could later add options for other colors
CGContextSetGrayFillColor(context, 0.0f, self.backgroundOpacity);
CGContextMoveToPoint(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMinY(boxRect)+shrink);
CGContextAddArc(context, CGRectGetMaxX(boxRect)-shrink - bRadius, CGRectGetMinY(boxRect)+shrink + bRadius, bRadius, 3 * (float)M_PI / 2, 0, 0);
CGContextAddArc(context, CGRectGetMaxX(boxRect)-shrink - bRadius, CGRectGetMaxY(boxRect)-shrink - bRadius, bRadius, 0, (float)M_PI / 2, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMaxY(boxRect)-shrink - bRadius, bRadius, (float)M_PI / 2, (float)M_PI, 0);
CGContextAddArc(context, CGRectGetMinX(boxRect)+shrink + bRadius, CGRectGetMinY(boxRect)+shrink + bRadius, bRadius, (float)M_PI, 3 * (float)M_PI / 2, 0);
CGContextClosePath(context);
CGContextFillPath(context);
当然,不是 boxRect 是完整的边界,你可以将它传递给你的方法并使用你想要的任何边界来绘制它。要使其成为三角形,您将只有 3 条线而不是两条线,并且您可能需要做一些数学运算来确定开始和结束角度。在盒子上,这些角度总是 90 度(这里给出的是 icky 弧度),但在三角形上,您要么必须即时计算角度,要么在三角形上有预设的纵横比,这样您就可以使用预设的开始和停止角度.在如图所示的示例中,有 3 个相等的角度,你会做 120 度或 M_PI/1.5 大小的步骤。
关于iphone - QuartzCore - 为多边形添加圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444044/