On a macOS (OSX) desktop app, I use NSBezierPath to draw a random closed shape which looks like this.
As you can see the dashed line shows the closed path which was drawn.
Now am trying to extract the masked image as per this path. But i get a small portion of the image. The masked image seems to correctly get the outline from the BezierPath. But size is an issue.
This is the method which returns the masked/clipped image. The sourceImage.size for this drawing - 1021 * 1031
- (NSImage *)imageByApplyingClippingBezierPath:(NSImage *)sourceImage
bezierPath:(NSBezierPath *)bezierPath
newFrame:(NSRect)newFrame
{
NSImage* newImage = [[NSImage alloc] initWithSize:newFrame.size];
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:newFrame.size.width
pixelsHigh:newFrame.size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:0
bitsPerPixel:0];
[newImage addRepresentation:rep];
[newImage lockFocus];
CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(context);
[bezierPath addClip];
NSRect targetFrame = NSMakeRect(0, 0, newFrame.size.width, newFrame.size.height);
[sourceImage drawInRect:targetFrame];
[newImage unlockFocus];
CGContextRestoreGState(context);
return newImage;
}
How can i get perfectly sized image outlined by the BezierPath? Any tips would be appreciated!
UPDATE
Just clarifying, how i draw the image. I get rectangle bounds of the bezier path and rectangular image cropped like this.
CGRect bezierBounds = CGPathGetPathBoundingBox([self.smartLassoWavyBezierPath quartzPath]);
NSRect targetFrame = NSMakeRect(0, 0, bezierBounds.size.width, bezierBounds.size.height);
NSImage *targetImage = [[NSImage alloc initWithSize:targetFrame.size];
[targetImage lockFocus];
[self.view.originalLoadImageOnCanvas
drawInRect:targetFrame fromRect:bezierBounds operation:NSCompositeCopy
fraction:1.0f];
[targetImage unlockFocus];