【问题标题】:iOS: How to draw a speical shapeiOS:如何绘制特殊形状
【发布时间】:2015-03-16 09:13:40
【问题描述】:

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

【问题讨论】:

标签: ios core-graphics uibezierpath


【解决方案1】:

首先,继承 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)

所有这些都给了你这个:

【讨论】:

  • 我最终编写了自己的视图和一个数据源委托来绘制它。虽然我不能发布我的所有代码,但它与您的解决方案类似
  • 我想指出,在 drawRect: 中绘制文本似乎是一种快速简便的方法,但这有一些含义,例如它不能被iOS,即 VoiceOver 不会看到此文本。所以我建议不要自己绘制文本,而是使用子视图,一个带有文本的简单 UILabel 应该可以解决问题。
猜你喜欢
  • 2022-11-22
  • 1970-01-01
  • 2012-07-09
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多