[英]Swift :- How to add offset to UIImageview inside UIScrollview in Swift?
In my iOS app, I have a scroll view which has the image view to scroll and zoom images.在我的 iOS 应用程序中,我有一个滚动视图,它具有滚动和缩放图像的图像视图。 What I am unable to do is launch the image view with pre-defined offset and zoom value.
我无法做的是使用预定义的偏移和缩放值启动图像视图。 Right now, on launch, the original image is shown which I can zoom-in/out and scroll, but I wanted to zoom-in/out with an offset with default values.
现在,在启动时,显示原始图像,我可以放大/缩小和滚动,但我想用默认值的偏移量放大/缩小。
On setting the scrollview.zoomScale
, I am not able to scroll the image completely.在设置
scrollview.zoomScale
,我无法完全滚动图像。 Code below:-以下代码:-
let scroller = UIScrollView()
scroller.translatesAutoresizingMaskIntoConstraints = false
scroller.minimumZoomScale = 1
scroller.maximumZoomScale = 5
return scroller
}()
let imageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
The first step:第一步:
scrollView = UIScrollView(frame: view.bounds)
view.addSubview(scrollView)
imageView.center = view.center
scrollView.addSubview(imageView)
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 2.0
scrollView.delegate = self
Step 2: implement the UIScrollViewDelegate method第二步:实现UIScrollViewDelegate方法
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
Finally:最后:
private func setImagePosition(_ image: UIImage) {
imageView.image = image
let size = imageSize(WithScreen: image)
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
scrollView?.contentSize = size
if let scrollView = scrollView, size.height < scrollView.bounds.size.height {
let offsetY = (scrollView.bounds.size.height - size.height) * 0.5
scrollView.contentInset = UIEdgeInsets(top: offsetY, left: 0, bottom: offsetY, right: 0)
}
}
private func imageSize(WithScreen image: UIImage) -> CGSize {
var size = UIScreen.main.bounds.size
size.height = image.size.height * size.width / image.size.width
return size
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.