iOS: 如何绘制特殊形状

iOS: How to draw a speical shape

如何使用UIBezierPath或CG绘制下图所示的形状?我可以想到几种方法,但是 none 都很好。它包含一个小 arrow/triangle 和一个圆圈。另外我需要能够旋转这个形状,所以箭头的角度不能硬编码。您可以忽略背景浅灰色圆圈。只是红色形状(加上 UILabel 更好)

首先,继承 UIView 并覆盖 drawRect:。这段代码非常接近,应该可以让您进行一些调整:

//Get the graphics context
let context = UIGraphicsGetCurrentContext()

//Colors, I was a little off here
let color = UIColor(red: 0.880, green: 0.653, blue: 0.653, alpha: 1.000)

//The circle
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(86, 31, 58, 56))
color.setFill()
ovalPath.fill()


//The pointed arrow on the left of the circle
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(87, 54))
bezierPath.addLineToPoint(CGPointMake(76, 60))
bezierPath.addLineToPoint(CGPointMake(87, 66))
bezierPath.addLineToPoint(CGPointMake(87, 54))
color.setFill()
bezierPath.fill()


//Now, draw the 17%
let textRect = CGRectMake(95, 45, 40, 29)
var textTextContent = NSString(string: "17%")
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Center

//Text components
let textFontAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(19), NSForegroundColorAttributeName: UIColor.whiteColor(), NSParagraphStyleAttributeName: textStyle]

let textTextHeight: CGFloat = textTextContent.boundingRectWithSize(CGSizeMake(textRect.width, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: textFontAttributes, context: nil).size.height
CGContextSaveGState(context)
CGContextClipToRect(context, textRect);
textTextContent.drawInRect(CGRectMake(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
CGContextRestoreGState(context)

所有这些都给了你这个: