我在 UIScrollView 中有一个 UIImageView。如何以编程方式将图像的 x,y 居中?
I have an UIImageView in an UIScrollView. How do I center at x,y of the image programmatically?
我在 UIScrollView 中有一个 UIImageView,图像的大小为 2000x3000。我可以在屏幕上捏缩放和拖动平移。 (我关注了这个视频https://www.youtube.com/watch?v=0Tz0vI721c8)。
我的问题是,如果我想以编程方式将显示集中在图像上的某个点(即 600、800),我想我需要使用 scrollView.setContentOffset(CGPoint),我该如何计算CG点?
// Assuming your image is the same width and height of
// the scrollview, the CGPoint for the center of the image will be
let scrollViewCenterX: CGFloat = scrollView.bounds.width / 2
let scrollViewCenterY: CGFloat = scrollView.bounds.height / 2
let imageCenterPoint = CGPoint(x: scrollViewCenterX, y: scrollViewCenterY)
scrollView.setContentOffset(imageCenterPoint)
// if we want to center the scrollview on `point`
let point = CGPoint(x: 600, y: 800)
let newPoint = CGPoint(x: point.x / 2, y: point.y / 2)
scrollView.setContentOffset(newPoint)
除了设置 .contentOffset
以匹配“目标中心点”之外,您还必须考虑几件事...
首先,目标...
使用这张 2000 x 3000
图片:
"
有了这组“中心点”:
let points: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 800, y: 600),
CGPoint(x: 1600, y: 1200),
CGPoint(x: 600, y: 2000),
CGPoint(x: 1900, y: 2900),
]
我们想以编程方式将中心设置为滚动视图的中心:
如果我们所做的只是将 .contentOffset
设置为 #3 的“目标点”,我们将得到:
所以,我们需要减去one-half滚动视图框的宽高:
scrollView.contentOffset.x = points[2].x - (scrollView.frame.width * 0.5)
scrollView.contentOffset.y = points[2].y - (scrollView.frame.height * 0.5)
这将我们的“目标点”置于滚动视图的中心,但是...
如果我们缩小到 90% (scrollView.zoomScale = 0.9
),我们会得到:
因此,我们需要将“目标点”转换为缩放比例:
// translate target point to zoomScale
var x: CGFloat = points[2].x * scrollView.zoomScale
var y: CGFloat = points[2].y * scrollView.zoomScale
x = x - (scrollView.frame.width * 0.5)
y = y - (scrollView.frame.height * 0.5)
scrollView.contentOffset.x = x
scrollView.contentOffset.y = y
而且,哇哦,我们有这个:
不过,下一个问题是我们不想让“目标点”居中,如果这会超出滚动视图限制的话。
例如,如果我们尝试以“1”或“5”为中心,我们会得到:
和:
点在滚动视图中居中,但只要我们触摸它进行滚动或缩放,它就会捕捉到角落。
我们需要限制 .contentOffset
以避免这种情况。
因此,对于点“1”(points[0]
):
// translate target point to zoomScale
var x: CGFloat = points[0].x * scrollView.zoomScale
var y: CGFloat = points[0].y * scrollView.zoomScale
// don't want to set offset below Zero
let minOffset: CGPoint = .zero
// don't want to set offset greater than what will fit in the scroll view
let maxOffset: CGPoint = CGPoint(x: imgView.frame.width - scrollView.frame.width, y: imgView.frame.height - scrollView.frame.height)
// this prevents x and from being negative
x = max(minOffset.x, x - (scrollView.frame.width * 0.5))
y = max(minOffset.y, y - (scrollView.frame.height * 0.5))
// this prevents x and y from exceeding the frame of the scroll view
x = min(maxOffset.x, x)
y = min(maxOffset.y, y)
scrollView.contentOffset.x = x
scrollView.contentOffset.y = y
这是一个完整的示例...如上图所示,点击“数字按钮”会将中心点滚动到滚动视图的中心(或尽可能靠近,如果它会超出限制) .您只需要添加 2000x3000 图像(名为“img2000x3000”)...不需要 @IBOutlet
或 @IBAction
连接:
class ScrollPosViewController: UIViewController, UIScrollViewDelegate {
let points: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 800, y: 600),
CGPoint(x: 1600, y: 1200),
CGPoint(x: 600, y: 2000),
CGPoint(x: 1900, y: 2900),
]
let scrollView: UIScrollView = {
let v = UIScrollView()
v.backgroundColor = .yellow
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let imgView: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemGreen
// make sure we can load the image
guard let img = UIImage(named: "img2000x3000") else {
print("Could not load image!!!")
return
}
// assing image to image view
imgView.image = img
// create a buttons stack view
let stack: UIStackView = {
let v = UIStackView()
v.distribution = .fillEqually
v.spacing = 20
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
for i in 0..<points.count {
let b = UIButton()
b.setTitle("\(i + 1)", for: [])
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.lightGray, for: .highlighted)
b.backgroundColor = .systemBlue
b.layer.cornerRadius = 8
b.addTarget(self, action: #selector(centerOn(_:)), for: .touchUpInside)
stack.addArrangedSubview(b)
}
// add image view to scroll view
scrollView.addSubview(imgView)
// add scroll view to view
view.addSubview(scrollView)
// add buttons stack view to view
view.addSubview(stack)
let g = view.safeAreaLayoutGuide
let c = scrollView.contentLayoutGuide
NSLayoutConstraint.activate([
// constrain background image view
// Leading / Trailing at 20-pts
scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
// height proportional to image size
scrollView.heightAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: img.size.height / img.size.width),
// centered vertically
scrollView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// constrain image view to all 4 sides of scroll view's Content Layout Guide
imgView.topAnchor.constraint(equalTo: c.topAnchor),
imgView.leadingAnchor.constraint(equalTo: c.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: c.trailingAnchor),
imgView.bottomAnchor.constraint(equalTo: c.bottomAnchor),
// constrain image view's width/height to image width/height
imgView.widthAnchor.constraint(equalToConstant: img.size.width),
imgView.heightAnchor.constraint(equalToConstant: img.size.height),
// constrain buttons stack view at bottom
stack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
stack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
stack.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
])
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 2.0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// update min zoom scale so we can only "zoom out" until
// the content view fits the scroll view frame
if scrollView.minimumZoomScale == 1.0 {
let xScale = scrollView.frame.width / imgView.frame.width
let yScale = scrollView.frame.height / imgView.frame.height
scrollView.minimumZoomScale = min(xScale, yScale)
}
}
@objc func centerOn(_ sender: Any?) -> Void {
guard let btn = sender as? UIButton,
let t = btn.currentTitle,
let n = Int(t),
n > 0,
n <= points.count
else {
return
}
// translate target point to zoomScale
var x: CGFloat = points[n - 1].x * scrollView.zoomScale
var y: CGFloat = points[n - 1].y * scrollView.zoomScale
// don't want to set offset below Zero
let minOffset: CGPoint = .zero
// don't want to set offset greater than what will fit in the scroll view
let maxOffset: CGPoint = CGPoint(x: imgView.frame.width - scrollView.frame.width, y: imgView.frame.height - scrollView.frame.height)
// this prevents x and from being negative
x = max(minOffset.x, x - (scrollView.frame.width * 0.5))
y = max(minOffset.y, y - (scrollView.frame.height * 0.5))
// this prevents x and y from exceeding the frame of the scroll view
x = min(maxOffset.x, x)
y = min(maxOffset.y, y)
// if we want to animate the point to the new offset
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseInOut], animations: {
// set the new content offset
self.scrollView.contentOffset = CGPoint(x: x, y: y)
}, completion: nil)
// or, without animation
// set the new content offset
//scrollView.contentOffset = CGPoint(x: x, y: y)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgView
}
}
我在 UIScrollView 中有一个 UIImageView,图像的大小为 2000x3000。我可以在屏幕上捏缩放和拖动平移。 (我关注了这个视频https://www.youtube.com/watch?v=0Tz0vI721c8)。
我的问题是,如果我想以编程方式将显示集中在图像上的某个点(即 600、800),我想我需要使用 scrollView.setContentOffset(CGPoint),我该如何计算CG点?
// Assuming your image is the same width and height of
// the scrollview, the CGPoint for the center of the image will be
let scrollViewCenterX: CGFloat = scrollView.bounds.width / 2
let scrollViewCenterY: CGFloat = scrollView.bounds.height / 2
let imageCenterPoint = CGPoint(x: scrollViewCenterX, y: scrollViewCenterY)
scrollView.setContentOffset(imageCenterPoint)
// if we want to center the scrollview on `point`
let point = CGPoint(x: 600, y: 800)
let newPoint = CGPoint(x: point.x / 2, y: point.y / 2)
scrollView.setContentOffset(newPoint)
除了设置 .contentOffset
以匹配“目标中心点”之外,您还必须考虑几件事...
首先,目标...
使用这张 2000 x 3000
图片:
"
有了这组“中心点”:
let points: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 800, y: 600),
CGPoint(x: 1600, y: 1200),
CGPoint(x: 600, y: 2000),
CGPoint(x: 1900, y: 2900),
]
我们想以编程方式将中心设置为滚动视图的中心:
如果我们所做的只是将 .contentOffset
设置为 #3 的“目标点”,我们将得到:
所以,我们需要减去one-half滚动视图框的宽高:
scrollView.contentOffset.x = points[2].x - (scrollView.frame.width * 0.5)
scrollView.contentOffset.y = points[2].y - (scrollView.frame.height * 0.5)
这将我们的“目标点”置于滚动视图的中心,但是...
如果我们缩小到 90% (scrollView.zoomScale = 0.9
),我们会得到:
因此,我们需要将“目标点”转换为缩放比例:
// translate target point to zoomScale
var x: CGFloat = points[2].x * scrollView.zoomScale
var y: CGFloat = points[2].y * scrollView.zoomScale
x = x - (scrollView.frame.width * 0.5)
y = y - (scrollView.frame.height * 0.5)
scrollView.contentOffset.x = x
scrollView.contentOffset.y = y
而且,哇哦,我们有这个:
不过,下一个问题是我们不想让“目标点”居中,如果这会超出滚动视图限制的话。
例如,如果我们尝试以“1”或“5”为中心,我们会得到:
和:
点在滚动视图中居中,但只要我们触摸它进行滚动或缩放,它就会捕捉到角落。
我们需要限制 .contentOffset
以避免这种情况。
因此,对于点“1”(points[0]
):
// translate target point to zoomScale
var x: CGFloat = points[0].x * scrollView.zoomScale
var y: CGFloat = points[0].y * scrollView.zoomScale
// don't want to set offset below Zero
let minOffset: CGPoint = .zero
// don't want to set offset greater than what will fit in the scroll view
let maxOffset: CGPoint = CGPoint(x: imgView.frame.width - scrollView.frame.width, y: imgView.frame.height - scrollView.frame.height)
// this prevents x and from being negative
x = max(minOffset.x, x - (scrollView.frame.width * 0.5))
y = max(minOffset.y, y - (scrollView.frame.height * 0.5))
// this prevents x and y from exceeding the frame of the scroll view
x = min(maxOffset.x, x)
y = min(maxOffset.y, y)
scrollView.contentOffset.x = x
scrollView.contentOffset.y = y
这是一个完整的示例...如上图所示,点击“数字按钮”会将中心点滚动到滚动视图的中心(或尽可能靠近,如果它会超出限制) .您只需要添加 2000x3000 图像(名为“img2000x3000”)...不需要 @IBOutlet
或 @IBAction
连接:
class ScrollPosViewController: UIViewController, UIScrollViewDelegate {
let points: [CGPoint] = [
CGPoint(x: 100, y: 100),
CGPoint(x: 800, y: 600),
CGPoint(x: 1600, y: 1200),
CGPoint(x: 600, y: 2000),
CGPoint(x: 1900, y: 2900),
]
let scrollView: UIScrollView = {
let v = UIScrollView()
v.backgroundColor = .yellow
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let imgView: UIImageView = {
let v = UIImageView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemGreen
// make sure we can load the image
guard let img = UIImage(named: "img2000x3000") else {
print("Could not load image!!!")
return
}
// assing image to image view
imgView.image = img
// create a buttons stack view
let stack: UIStackView = {
let v = UIStackView()
v.distribution = .fillEqually
v.spacing = 20
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
for i in 0..<points.count {
let b = UIButton()
b.setTitle("\(i + 1)", for: [])
b.setTitleColor(.white, for: .normal)
b.setTitleColor(.lightGray, for: .highlighted)
b.backgroundColor = .systemBlue
b.layer.cornerRadius = 8
b.addTarget(self, action: #selector(centerOn(_:)), for: .touchUpInside)
stack.addArrangedSubview(b)
}
// add image view to scroll view
scrollView.addSubview(imgView)
// add scroll view to view
view.addSubview(scrollView)
// add buttons stack view to view
view.addSubview(stack)
let g = view.safeAreaLayoutGuide
let c = scrollView.contentLayoutGuide
NSLayoutConstraint.activate([
// constrain background image view
// Leading / Trailing at 20-pts
scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
// height proportional to image size
scrollView.heightAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: img.size.height / img.size.width),
// centered vertically
scrollView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// constrain image view to all 4 sides of scroll view's Content Layout Guide
imgView.topAnchor.constraint(equalTo: c.topAnchor),
imgView.leadingAnchor.constraint(equalTo: c.leadingAnchor),
imgView.trailingAnchor.constraint(equalTo: c.trailingAnchor),
imgView.bottomAnchor.constraint(equalTo: c.bottomAnchor),
// constrain image view's width/height to image width/height
imgView.widthAnchor.constraint(equalToConstant: img.size.width),
imgView.heightAnchor.constraint(equalToConstant: img.size.height),
// constrain buttons stack view at bottom
stack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
stack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
stack.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
])
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 2.0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// update min zoom scale so we can only "zoom out" until
// the content view fits the scroll view frame
if scrollView.minimumZoomScale == 1.0 {
let xScale = scrollView.frame.width / imgView.frame.width
let yScale = scrollView.frame.height / imgView.frame.height
scrollView.minimumZoomScale = min(xScale, yScale)
}
}
@objc func centerOn(_ sender: Any?) -> Void {
guard let btn = sender as? UIButton,
let t = btn.currentTitle,
let n = Int(t),
n > 0,
n <= points.count
else {
return
}
// translate target point to zoomScale
var x: CGFloat = points[n - 1].x * scrollView.zoomScale
var y: CGFloat = points[n - 1].y * scrollView.zoomScale
// don't want to set offset below Zero
let minOffset: CGPoint = .zero
// don't want to set offset greater than what will fit in the scroll view
let maxOffset: CGPoint = CGPoint(x: imgView.frame.width - scrollView.frame.width, y: imgView.frame.height - scrollView.frame.height)
// this prevents x and from being negative
x = max(minOffset.x, x - (scrollView.frame.width * 0.5))
y = max(minOffset.y, y - (scrollView.frame.height * 0.5))
// this prevents x and y from exceeding the frame of the scroll view
x = min(maxOffset.x, x)
y = min(maxOffset.y, y)
// if we want to animate the point to the new offset
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseInOut], animations: {
// set the new content offset
self.scrollView.contentOffset = CGPoint(x: x, y: y)
}, completion: nil)
// or, without animation
// set the new content offset
//scrollView.contentOffset = CGPoint(x: x, y: y)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgView
}
}