[英]Rotating an image view which should be inside an arc with fixed point for bottom
I am creating a speed gauge.我正在创建一个速度计。 The bottom of my image has to be in a center point of my arc and I need to rotate the image with a fixed center point.我的图像的底部必须在我的弧线的中心点,我需要用固定的中心点旋转图像。 I don't know how to to do it.我不知道该怎么做。
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)
}
Here is my code where I am trying to center image inside the arc but my image is in the left corner instead.这是我的代码,我试图在弧内居中图像,但我的图像位于左角。
To rotation I was trying to use旋转我试图使用
handImageView.transform = CGAffineTransform(rotationAngle: deg2rad(handRotation))
but nothing working properly.但没有任何工作正常。 Please help me with settting my image in the center of arc and then rotating its.请帮助我将我的图像设置在弧的中心,然后旋转它。
With this line:有了这条线:
handImageView.layer.anchorPoint = CGPoint(x: 0, y: 0.5)
you've set the anchor point to the Left Edge and Vertical Center您已将锚点设置为左边缘和垂直中心
Change it to this:将其更改为:
// set the anchorPoint to Horizontal Center / Bottom Edge
handImageView.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0)
and see if you get the rotation you want.看看你是否得到你想要的旋转。
Here's a complete example... the arrow starts at Zero-degrees (pointing up) -- each tap will increment the rotation by 10-degrees:这是一个完整的例子……箭头从零度开始(指向上方)——每次点击都会将旋转增加 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.