作者:白人冰娟 | 来源:互联网 | 2022-10-23 19:31
我需要将灰色视图内的红色视图放大到滚动视图内的给定红色边界(在这种情况下,滚动视图边框取决于给定的宽度/高度比),同时保持视图的可见尺寸不变。他们还应该始终触摸绿色边框。
我尝试在此视图上使用缩放变换来实现此目的,以便在放大滚动视图时,我使用公式1 / zoomScale
并更改其锚点来缩小此视图,以使其保持绿色边框。
问题是在进行所有这些操作后,我不知道如何为红色视图计算目标边界rect,因此我可以使用适当的滚动到它zoomScale
。
请在此处查看完整的演示项目
编辑
灰度视图可能会缩小滚动视图边界(请参见上一张图片),主要是要在滚动视图边界内放入由红色视图包围的绿色矩形(您可能会认为它们是绿色区域的负插图),因此我们应该实际计算考虑到绿色矩形的起始和结束尺寸,应将红色视图“固定”到该矩形。
基本方法
- (void)adjustScrollPositionAndZoomToFrame:(CGRect)frame
{
CGFloat viewWidth = frame.size.width;
CGFloat viewHeight = frame.size.height;
CGFloat scrollViewWidth = self.scrollView.frame.size.width;
CGFloat scrollViewHeight = self.scrollView.frame.size.height;
CGSize newSize = [self scaleSize:frame.size toHeight:scrollViewHeight];
if (newSize.width > scrollViewWidth) {
newSize = [self scaleSize:frame.size toWidth:scrollViewWidth];
}
CGFloat scaleFactor = newSize.height == scrollViewHeight
? scrollViewHeight / viewHeight
: scrollViewWidth / viewWidth;
[self scrollRect:frame toCenterInScrollView:self.scrollView animated:NO];
self.scrollView.zoomScale = scaleFactor;
}
缩放比例
- (void)handleZoom:(CGFloat)zoom
{
NSArray *anchorPoints = @[[NSValue valueWithCGPoint:CGPointMake(1.0, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 1.0)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 0.5)],
[NSValue valueWithCGPoint:CGPointMake(1.0, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.5, 0.0)],
[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)]
];
for (UILabel *label in _labels) {
[self setViewAnchorPoint:label value:[anchorPoints[[_labels indexOfObject:label]] CGPointValue]];
label.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1 / zoom, 1 / zoom);
}
}
/**
* @see /sf/ask/17360801/
* @param value See view.layer.anchorPoint
*/
- (void)setViewAnchorPoint:(UIView *)view value:(CGPoint)value
{
CGPoint newPoint = CGPointMake(view.bounds.size.width * value.x,
view.bounds.size.height * value.y);
CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x,
view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
CGPoint position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = value;
}
变焦前的初始场景:
变焦后我有什么:
变焦后我需要什么: