【问题标题】:How to center text in the middle of a circle?如何使文本在圆圈中间居中?
【发布时间】:2015-11-05 09:49:37
【问题描述】:

我制作了一个圆形类,但我想将文本放在它的直接中心。

字体大小无关紧要,文本应始终显示在中心。

到目前为止,我只是尝试了任意值,直到它足够靠近中心。必须有更简单的方法。

import UIKit


class CircleView: UIView {
let circleLayer: CAShapeLayer  = CAShapeLayer()

init(frame: CGRect, innerColor: CGColor = Colors.colorWithHexString("#858585").CGColor, rimColor: CGColor = UIColor.blueColor().CGColor) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.clearColor()
    let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)

    // Setup the CAShapeLayer
    circleLayer.path = circlePath.CGPath
    circleLayer.fillColor = innerColor
    circleLayer.strokeColor = rimColor
    circleLayer.lineWidth = 5.0

    // Don't draw the circle at start
    circleLayer.strokeEnd = 1.0
    layer.addSublayer(circleLayer)
}

func animateCircle(duration: NSTimeInterval) {
    let animation = CABasicAnimation(keyPath: "strokeEnd")

    animation.duration = duration

    animation.fromValue = 0
    animation.toValue = 1

    // Do a linear animation 
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

    circleLayer.strokeEnd = 1.0

    // Do the actual animation
    circleLayer.addAnimation(animation, forKey: "animateCircle")
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

【问题讨论】:

  • 我没有在您的代码中看到 any 文本。我错过了什么吗?

标签: ios swift uilabel calayer uibezierpath


【解决方案1】:

假设您的视图中有一个名为labelUILabel 属性;您可以在layoutSubviews 方法中将center 值设置为视图的中心:

override func layoutSubviews() {
    super.layoutSubviews()

    label.sizeToFit()
    label.center = self.convertPoint(self.center, fromView: self.superview)
}

请注意,使用Auto Layout 会更容易,但您无法像上面那样更改任何框架或中心:

self.addConstraint(NSLayoutConstraint(
    item: label, 
    attribute: NSLayoutAttribute.CenterX, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: self, 
    attribute:  NSLayoutAttribute.CenterX, 
    multiplier: 1.0, constant: 0.0))

self.addConstraint(NSLayoutConstraint(
    item: label, 
    attribute: NSLayoutAttribute.CenterY, 
    relatedBy: NSLayoutRelation.Equal, 
    toItem: self, 
    attribute:  NSLayoutAttribute.CenterY, 
    multiplier: 1.0, constant: 0.0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2022-07-15
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多