问题描述
我正在创建一个速度计。我的图像的底部必须在我的弧的中心点,我需要用一个固定的中心点旋转图像。我不知道该怎么做。
private func drawHand(center: CGPoint) {
let handImage = UIImage(named: "hand")
handImageView = UIImageView(image: handImage)
handImageView.translatesAutoresizingMaskIntoConstraints = false
handImageView.bounds = CGRect(x: center.x,y: center.y,width: 100,height: bounds.height / 3)
handImageView.layer.anchorPoint = CGPoint(x: 0,y: 0.5)
handImageView.center = CGPoint(x: bounds.midX,y: bounds.midY)
addSubview(handImageView)
}
这是我的代码,我试图在圆弧内居中图像,但我的图像在左角。
旋转我试图使用
handImageView.transform = CGAffineTransform(rotationAngle: deg2rad(handRotation))
但没有任何工作正常。 请帮我将图像设置在圆弧的中心,然后旋转它。
解决方法
使用这一行:
handImageView.layer.anchorPoint = CGPoint(x: 0,y: 0.5)
您已将锚点设置为左边缘和垂直中心
改成这样:
// set the anchorPoint to Horizontal Center / Bottom Edge
handImageView.layer.anchorPoint = CGPoint(x: 0.5,y: 1.0)
看看你是否得到了你想要的旋转。
这是一个完整的例子……箭头从零度开始(指向上)——每次点击都会使旋转增加 10 度:
extension Double {
var degreesToRadians: Self { self * .pi / 180 }
var radiansToDegrees: Self { self * 180 / .pi }
}
class ViewController: UIViewController {
var handImageView: UIImageView!
var handRotation: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
let handImage = UIImage(systemName: "arrow.up")
handImageView = UIImageView(image: handImage)
// so we can see the image view frame
handImageView.backgroundColor = .systemYellow
view.addSubview(handImageView)
// set imageView frame to 80 x 160
handImageView.frame = CGRect(origin: .zero,size: CGSize(width: 80,height: 160))
// set the anchorPoint to Horizontal Center / Bottom Edge
handImageView.layer.anchorPoint = CGPoint(x: 0.5,y: 1.0)
// set image view's Anchor Point to the center of the view
handImageView.center = view.center
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
// increment rotation by 10-degrees with each touch
// Zero-degrees is pointing UP (12 o'clock)
handRotation += 10
handImageView.transform = CGAffineTransform(rotationAngle: CGFloat(handRotation.degreesToRadians))
print("rotation:",handRotation)
}
}