Last active
August 29, 2015 14:10
-
-
Save itod/9960ecb1acf1f6203167 to your computer and use it in GitHub Desktop.
Some View-centering code for a Canvas in an NSScrollView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| BOOL TDSizeContainsSize(CGSize s1, CGSize s2) { | |
| return s1.width >= s2.width && s1.height >= s2.height; | |
| } | |
| CGRect TDSquareAroundPoint(CGPoint p, CGFloat side) { | |
| CGRect r = CGRectMake(p.x - side*0.5, p.y - side*0.5, side, side); | |
| return r; | |
| } | |
| CGPoint TDRectGetCenter(CGRect r) { | |
| return CGPointMake(NSMidX(r), NSMidY(r)); | |
| } | |
| @implementation CanvasView | |
| … | |
| - (void)setFrame:(CGRect)newFrame { | |
| // center composition in scrollview | |
| NSClipView *cv = (NSClipView *)[self superview]; | |
| TDAssert([cv isKindOfClass:[NSClipView class]]); | |
| CGRect compFrame = [self scaledCompositionFrame]; | |
| // calc desired frame | |
| { | |
| CGSize superSize = cv.frame.size; | |
| CGSize scrollSize = compFrame.size; | |
| CGFloat margin = 0.0; | |
| if (TDSizeContainsSize(compFrame.size, scrollSize)) { | |
| margin = (CANVAS_MARGIN * 2.0)*[self currentZoomScale]; | |
| } | |
| scrollSize.width += margin; | |
| scrollSize.height += margin; | |
| newFrame.size.width = MAX(scrollSize.width, superSize.width); | |
| newFrame.size.height = MAX(scrollSize.height, superSize.height); | |
| } | |
| [super setFrame:newFrame]; | |
| [[self horizontalRulerView] setOriginOffset:compFrame.origin.x]; | |
| [[self verticalRulerView] setOriginOffset:compFrame.origin.y]; | |
| [self scrollToCenter]; | |
| } | |
| - (void)scrollToCenter { | |
| CGPoint centerPoint; | |
| if (_manipulator) { | |
| // if there's a selection, center around that | |
| centerPoint = [self convertPointFromComposition:_manipulator.center]; | |
| } else { | |
| // else center around center of comp | |
| centerPoint = [self convertPointFromComposition:_composition.center]; | |
| } | |
| //CGRect vizRect = [self visibleRect]; | |
| //if (!CGRectContainsRect(vizRect, centerRect)) { | |
| [self scrollPointToCenter:centerPoint]; | |
| [[[self window] windowController] invalidateRestorableState]; | |
| //} | |
| } | |
| - (void)scrollRectToCenter:(CGRect)r { | |
| CGRect vizRect = [self visibleRect]; | |
| if (TDSizeContainsSize(vizRect.size, r.size)) { | |
| CGPoint p = TDRectGetCenter(r); | |
| r = CGRectMake(p.x - vizRect.size.width*0.5, p.y - vizRect.size.height*0.5, vizRect.size.width, vizRect.size.height); | |
| } | |
| [self scrollRectToVisible:r]; | |
| } | |
| - (void)scrollPointToCenter:(CGPoint)p { | |
| [self scrollRectToCenter:TDSquareAroundPoint(p, 2.0)]; | |
| } | |
| … | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment