gpt4 book ai didi

ios - UIView bounds.applying 但旋转

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:21 24 4
gpt4 key购买 nike

我想在 View 周围创建虚线边框,可以移动/旋转/缩放。

这是我的代码:

func addBorder() {        
let f = selectedObject.bounds.applying(selectedObject.transform)
borderView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) //just for testing
borderView.frame = f
borderView.center = selectedObject.center
borderView.transform = CGAffineTransform(translationX: selectedObject.transform.tx, y: selectedObject.transform.ty)

removeBorder() //remove old border

let f2 = CGRect(x: 0, y: 0, width: borderView.frame.width, height: borderView.frame.height)
let dashedBorder = CAShapeLayer()
dashedBorder.strokeColor = UIColor.black.cgColor
dashedBorder.lineDashPattern = [2, 2]
dashedBorder.frame = f2
dashedBorder.fillColor = nil
dashedBorder.path = UIBezierPath(rect: f2).cgPath
dashedBorder.name = "border"
borderView.layer.addSublayer(dashedBorder)
}

它看起来像这样: enter image description here

这还不错,但我希望边框也旋转,因为它可能会误导用户,因为触摸区域仅在图像上。

我尝试将旋转应用于变换:

func addBorder() {        
let f = selectedObject.bounds.applying(selectedObject.transform)
borderView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) //just for testing
borderView.frame = f
borderView.center = selectedObject.center
let rotation = atan2(selectedObject.transform.b, selectedObject.transform.a)

borderView.transform = CGAffineTransform(rotationAngle: rotation).translatedBy(x: selectedObject.transform.tx, y: selectedObject.transform.ty)

removeBorder() //remove old border

let f2 = CGRect(x: 0, y: 0, width: borderView.frame.width, height: borderView.frame.height)
let dashedBorder = CAShapeLayer()
dashedBorder.strokeColor = UIColor.black.cgColor
dashedBorder.lineDashPattern = [2, 2]
dashedBorder.frame = f2
dashedBorder.fillColor = nil
dashedBorder.path = UIBezierPath(rect: f2).cgPath
dashedBorder.name = "border"
borderView.layer.addSublayer(dashedBorder)
}

但旋转之后它看起来像这样:

enter image description here

我该如何解决这个问题?

最佳答案

这是一个基于您的代码的示例:

//initial transforms
selectedObject.transform = CGAffineTransform.init(rotationAngle: .pi / 4).translatedBy(x: 150, y: 15)

func addBorder() {
let borderView = UIView.init(frame: selectedObject.bounds)
self.view.addSubview(borderView)
borderView.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) //just for testing
borderView.center = selectedObject.center
borderView.transform = selectedObject.transform

removeBorder() //remove old border

let dashedBorder = CAShapeLayer()
dashedBorder.strokeColor = UIColor.black.cgColor
dashedBorder.lineDashPattern = [2, 2]
dashedBorder.fillColor = nil
dashedBorder.path = UIBezierPath(rect: borderView.bounds).cgPath
dashedBorder.name = "border"
borderView.layer.addSublayer(dashedBorder)
}

关于ios - UIView bounds.applying 但旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52589657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com