【问题标题】:How can I rotate a CATextLayer properly in Swift?如何在 Swift 中正确旋转 CATextLayer?
【发布时间】:2019-11-04 02:46:27
【问题描述】:

我目前面临一个问题,即在旋转 CATextLayer 时,帧大小会同时发生意外转换。我希望文本可以以某个角度旋转而不改变其框架大小。如果有人能告诉我这件事,在此先感谢。

我尝试过的:

var someAngle: CGFloat = 0 {
    didSet {
        drawText()
    }
}

func drawText() {

    for layer in someView.layer.sublayers ?? [] where layer is CATextLayer {
        layer.removeFromSuperlayer()
    }

    let textLayer = CATextLayer()
    textLayer.fontSize = 26
    textLayer.backgroundColor = UIColor.lightGray.cgColor
    textLayer.string = "Hello world"
    textLayer.alignmentMode = .center

    textLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    textLayer.transform = CATransform3DMakeRotation(someAngle, 0.0, 0.0, 1.0)

    let textSize = calculateTextSize(text: "Hello world", font: UIFont.systemFont(ofSize: 26))
    let origin = CGPoint(x: someView.bounds.midX - textSize.width/2, y: someView.bounds.midY - textSize.height/2)
    textLayer.frame = CGRect(origin: origin, size: textSize)

    someView.layer.addSublayer(textLayer)
}

但是,结果如下所示:

而我的期望与此类似:

【问题讨论】:

  • 你在哪里有 shapeLayer?您只是为 textLayer 单独设置背景颜色,对吗?
  • 没错。没有shapeLayer,我只设置了背景颜色。但是如您所见,textLayer 框架在更新其旋转角度时发生了很大变化。
  • 那是因为你已经对图层本身应用了变换。没有办法单独获得背景而不改变。您可能需要为形状再添加一层。
  • “帧大小会同时发生意外变化”。这并不意外。好吧,也许你没想到。但是当应用变换时,框架的概念就失去了意义。它不能用于任何事情。它仅表示边界框。

标签: ios swift catransform3d catextlayer


【解决方案1】:

通过在函数外部添加一个 textLayer 属性解决了这个问题。

var textLayer = CATextLayer()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    相关资源
    最近更新 更多