我有一个UIImageView在draw函数中旋转。
public var progress: CGFloat = 0 {
didSet {
setNeedsDisplay()
}
}
override public func draw(_ rect: CGRect) {
rotateIcon(by: progress)
}
private func rotateIcon(by angle: CGFloat) {
if imageView == nil {
imageView = UIImageView(image: UIImage(named: "bt_info"))
imageView?.center = center
imageView?.frame.size = CGSize(width: 24.0, height: 24.0)
addSubview(imageView!)
}
imageView?.transform = CGAffineTransform(rotationAngle: angle)
}下面是为上面的片段附加的输出。

当我设置帧大小时,imageView在旋转时会收缩和扩展。我想在imageView旋转时保持大小。我遗漏了什么?
发布于 2022-03-10 20:40:26
好的-你在问题中发布的代码与Dropbox项目中的代码不匹配.
在你的项目中,你要这样做:
private func rotateScannerIcon(by angle: CGFloat) {
if testView == nil {
testView = UIView()
testView?.backgroundColor = .red
addSubview(testView!)
}
let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY)
testView?.center = centerPoint
testView?.frame.size = CGSize(width: 24.0, height: 24.0)
testView?.transform = CGAffineTransform(rotationAngle: angle)
}使用该代码,在应用了旋转转换后,您将更改帧大小.而实际的景观不再是“方形”了。
如果您在"create“块中移动位置/大小代码:
private func rotateScannerIcon(by angle: CGFloat) {
if testView == nil {
testView = UIView()
testView?.backgroundColor = .red
addSubview(testView!)
let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY)
testView?.center = centerPoint
testView?.frame.size = CGSize(width: 24.0, height: 24.0)
}
testView?.transform = CGAffineTransform(rotationAngle: angle)
}框架的“挤压”不再发生。
然而,覆盖draw()可能不是最好的方法。这主要是在UIKit视图更新不足以处理布局时完成的,例如在路径上使用笔画/填充时。
所以,我建议你做些改变。
初始化自定义视图子类时创建您的子视图(UIView或UIImageView或其他什么),并使用自动布局约束对其大小/位置进行限制。
然后,在更新progress属性时,应用旋转转换。
举个例子,下面是TestView类的修改版本:
public class TestView: UIView {
public var progress: CGFloat = 0 {
didSet {
rotateScannerIcon(by: (progress * CGFloat(Double.pi)))
}
}
internal var testView: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
// create the view (or image view)
testView = UIView()
testView.backgroundColor = .red
// add it to self
addSubview(testView)
// let's use auto-layout constraints
testView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// constrain the view to 24 x 24, centered in self
testView.widthAnchor.constraint(equalToConstant: 24.0),
testView.heightAnchor.constraint(equalTo: testView.widthAnchor),
testView.centerXAnchor.constraint(equalTo: centerXAnchor),
testView.centerYAnchor.constraint(equalTo: centerYAnchor),
])
}
private func rotateScannerIcon(by angle: CGFloat) {
testView.transform = CGAffineTransform(rotationAngle: angle)
}
}https://stackoverflow.com/questions/71421578
复制相似问题