In my program I'm drawing some shapes inside an NSView using NSBezierPath. Everything works and looks great except when I resize the window.

Example

Initial drawing

Initial drawing

Window resize Window resize

Does anyone know what I should use to prevent this square from being anchored to the initial position, but make it readjust relative the the initial scale.

Any help is appreciated!

有帮助吗?

解决方案

If you are doing your drawing in drawRect: then the answer is NO. You will need to rebuild and reposition your path each time. What you can do is something along the following lines:

- (void) drawRect:(NSRect)dirtyRect
{
    // Assuming that _relPos with x and y having values bewteen 0 and 1.
    // To keep the square in the middle of the view you would set _relPos to
    // CGPointMake(0.5, 0.5).

    CGRect bounds = self.bounds;

    CGRect rect;
    rect.size.width  = 100;
    rect.size.height = 100;
    rect.origin.x = bounds.origin.x + bounds.size.width  * _relPos.x - rect.size.width /2;
    rect.origin.y = bounds.origin.y + bounds.size.height * _relPos.y - rect.size.height/2;

    NSBezierPath *path = [NSBezierPath bezierPathWithRect:rect];
    [[NSColor redColor] set];
    path.lineWidth = 2; 
    [path stroke];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top