我有一个应用程序,用户可以将形状放在图像上。该图像位于设置为AspectFit的UIImageView中。 UIImageView位于UIScrollView中,允许缩放和平移。形状是UIViews添加到UIImageView。除非设备方向发生变化,否则一切正常。由于图像设置为AspectFit,因此方向也会改变宽高比。因此,我的形状不会在图像上保持相同的位置。
ViewController代码:
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = markupUIImage;
scrollView.maximumZoomScale=5;
scrollView.minimumZoomScale=0.5;
scrollView.bounces=true;
scrollView.bouncesZoom=true;
scrollView.contentSize=CGSize(width: imageView.frame.size.width, height: imageView.frame.size.height);
scrollView.showsHorizontalScrollIndicator=true;
scrollView.showsVerticalScrollIndicator=true;
scrollView.delegate=self;
}
func viewForZooming(in scrollView: UIScrollView) -> UIView?
{
return self.imageView
}
形状类:
class ShapeUIView: UIView {
override public class var layerClass: Swift.AnyClass {
get {
return CAShapeLayer.self;
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeView()
}
private func initializeView(){
let shapeLayer = (layer as! CAShapeLayer);
shapeLayer.opacity = 1.0
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineWidth = 2.0
shapeLayer.strokeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor
shapeLayer.fillColor = UIColor(red: 0, green: 128, blue: 0, alpha: 0.3).cgColor
self.isUserInteractionEnabled = true;
self.alpha = 1.0;
self.isHidden = false;
}
public func setPath(_ path: UIBezierPath) {
(layer as! CAShapeLayer).path = path.cgPath;
}
}
旋转后如何让形状保持在图像上的相同位置?
答案 0 :(得分:0)
我能够找出自己的问题。发布在这里以防其他人遇到这个。
我所做的是设置UIImageView.contentMode = .center
并将UIImageView大小设置为图像的相同高度和宽度。然后我让UIScrollView做它的事情并缩放图像。因此,由于AspectFit和UIScrollView缩放图像,我没有UIImageView缩放图像。
我把以下内容放在我的UIViewController中:
override func viewDidAppear(_ animated: Bool) {
//Initial Scale
imageView.bounds.size.width = (imageView.image?.size.width)!;
imageView.bounds.size.height = (imageView.image?.size.height)!;
imageView.frame = CGRect(x: 0, y: 0, width: imageView.bounds.size.width, height: imageView.bounds.size.height)
let widthScale: CGFloat = scrollView.width / imageView.image!.size.width;
let heightScale: CGFloat = scrollView.height / imageView.image!.size.height;
let initialZoom = min(widthScale, heightScale);
scrollView.setZoomScale(initialZoom, animated: false)
}
现在,当我的形状在图像上绘制并且设备旋转时,它们会保持在正确的位置。