How to maintain the scroll position in NSScrollView when changing scale?

后端 未结 3 1279
心在旅途
心在旅途 2020-12-24 03:22

I\'ve got an NSView (myView) wrapped in an NSScrollView (myScrollView). Using zoom-in/out buttons, the user can alter the scale of myView. If the user is currently scrolle

3条回答
  •  有刺的猬
    2020-12-24 03:56

    This is an old question, but I hope someone looking for this finds my answer useful...

    float zoomFactor = 1.3;
    
    -(void)zoomIn
    {
        NSRect visible = [scrollView documentVisibleRect];
        NSRect newrect = NSInsetRect(visible, NSWidth(visible)*(1 - 1/zoomFactor)/2.0, NSHeight(visible)*(1 - 1/zoomFactor)/2.0);
        NSRect frame = [scrollView.documentView frame];
    
        [scrollView.documentView scaleUnitSquareToSize:NSMakeSize(zoomFactor, zoomFactor)];
        [scrollView.documentView setFrame:NSMakeRect(0, 0, frame.size.width * zoomFactor, frame.size.height * zoomFactor)];
    
        [[scrollView documentView] scrollPoint:newrect.origin];
    }
    
    -(void)zoomOut
    {
        NSRect visible = [scrollView documentVisibleRect];
        NSRect newrect = NSOffsetRect(visible, -NSWidth(visible)*(zoomFactor - 1)/2.0, -NSHeight(visible)*(zoomFactor - 1)/2.0);
    
        NSRect frame = [scrollView.documentView frame];
    
        [scrollView.documentView scaleUnitSquareToSize:NSMakeSize(1/zoomFactor, 1/zoomFactor)];
        [scrollView.documentView setFrame:NSMakeRect(0, 0, frame.size.width / zoomFactor, frame.size.height / zoomFactor)];
    
        [[scrollView documentView] scrollPoint:newrect.origin];
    }
    

提交回复
热议问题