【发布时间】:2020-09-26 09:24:10
【问题描述】:
我正在尝试构建一个控件,例如附加的圆形图像,其中多个段的每个部分具有相等的空间。段数可以根据提供的数组而改变。
到目前为止,我已经使用 CAShapeLayer 和 UIBezierPath 开发了这个。还在每个形状图层的中心添加了文本。 到目前为止,我已经添加了用于生成此控件的代码。
let circleLayer = CALayer()
func createCircle(_ titleArray:[String]) {
update(bounds: bounds, titleArray: titleArray)
containerView.layer.addSublayer(circleRenderer.circleLayer)
}
func update(bounds: CGRect, titleArray: [String]) {
let position = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
circleLayer.position = position
circleLayer.bounds = bounds
update(titleArray: titles)
}
func update(titleArray: [String]) {
let center = CGPoint(x: circleLayer.bounds.size.width / 2.0, y: circleLayer.bounds.size.height / 2.0)
let radius:CGFloat = min(circleLayer.bounds.size.width, circleLayer.bounds.size.height) / 2
let segmentSize = CGFloat((Double.pi*2) / Double(titleArray.count))
for i in 0..<titleArray.count {
let startAngle = segmentSize*CGFloat(i) - segmentSize/2
let endAngle = segmentSize*CGFloat(i+1) - segmentSize/2
let midAngle = (startAngle+endAngle)/2
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.random.cgColor
let bezierPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
bezierPath.addLine(to: center)
shapeLayer.path = bezierPath.cgPath
let height = titleArray[i].height(withConstrainedWidth: radius-20, font: UIFont.systemFont(ofSize: 15))
let frame = shapeLayer.path?.boundingBoxOfPath ?? CGRect.zero
let textLayer = TextLayer()
textLayer.frame = CGRect(x: 0, y: 0, width: 70, height: height)
textLayer.position = CGPoint(x: frame.center.x, y: frame.center.y)
textLayer.fontSize = 15
textLayer.contentsScale = UIScreen.main.scale
textLayer.alignmentMode = .center
textLayer.string = titleArray[i]
textLayer.isWrapped = true
textLayer.backgroundColor = UIColor.black.cgColor
textLayer.foregroundColor = UIColor.white.cgColor
textLayer.transform = CATransform3DMakeRotation(midAngle, 0.0, 0.0, 1.0)
shapeLayer.addSublayer(textLayer)
circleLayer.addSublayer(shapeLayer)
}
}
circleLayer 添加为superlayer,包含 UIView 的整个区域。
我的要求是在带有角度的形状内添加垂直和水平居中的文本。我遇到了在形状内居中文本的问题,而角度很好。
谢谢
【问题讨论】:
-
如果您需要这方面的帮助,请尝试包含足够的代码来生成您目前所拥有的内容。见minimal reproducible example。
-
图层通常围绕其中心旋转。如果剪切旋转代码,文本图层是否正确定位(居中)?
-
@matt 不,即使我剪切了旋转代码,文本看起来也不会为图层居中。我将添加另一个没有旋转代码的图像。
-
不需要。关键是,您只需要从正确的中心开始即可。中心在旋转过程中不会移动(通常),所以如果你在没有旋转的情况下获得正确的位置,它也会在旋转时正确。
标签: ios swift cashapelayer quartz-core catextlayer