我有一个包裹在 NSScrollView (myScrollView) 中的 NSView (myView)。使用放大/缩小按钮,用户可以更改 myView 的比例。如果用户当前滚动到 myView 中的特定位置,我想在缩放发生后将该部分视图保留在屏幕上。
我的代码如下所示:
// preserve current position in scrollview
NSRect oldVisibleRect = [[myScrollView contentView] documentVisibleRect];
NSPoint oldCenter = NSPointFromCGPoint(CGPointMake(oldVisibleRect.origin.x + (oldVisibleRect.size.width / 2.0),
oldVisibleRect.origin.y + (oldVisibleRect.size.height / 2.0)));
// adjust my zoom
++displayZoom;
[self scaleUnitSquareToSize:NSSizeFromCGSize(CGSizeMake(0.5, 0.5))];
[self calculateBounds]; // make sure my frame & bounds are at least as big as the visible content view
[self display];
// Adjust scroll view to keep the same position.
NSRect newVisibleRect = [[myScrollView contentView] documentVisibleRect];
NSPoint newOffset = NSPointFromCGPoint(CGPointMake((oldCenter.x * 0.5) - (newVisibleRect.size.width / 2.0),
(oldCenter.y * 0.5) - (newVisibleRect.size.height / 2.0)));
if (newOffset.x < 0)
newOffset.x = 0;
if (newOffset.y < 0)
newOffset.y = 0;
[[myScrollView contentView] scrollToPoint: newOffset];
[myScrollView reflectScrolledClipView: [myScrollView contentView]];
它似乎有点接近,但它并不完全正确,我无法弄清楚我做错了什么。我的两个问题是:
1)是否没有内置的东西:
[myView adjustScaleBy: 0.5 whilePreservingLocationInScrollview:myScrollView];
2)如果没有,任何人都可以看到我在上面的“漫长”方法中做错了什么吗?
谢谢!