在macOS(OSX)桌面应用程序上,我使用NSBezierPath绘制看起来像这样的随机封闭形状。
如您所见,虚线显示绘制的闭合路径。
现在正在尝试按照此路径提取蒙版图像。但是我得到了一小部分图像。遮罩的图像似乎可以从BezierPath正确获取轮廓。但是大小是个问题。
这是返回被遮罩/剪切的图像的方法。此图形的sourceImage.size-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;
}
如何获得由BezierPath绘制的尺寸合适的图像?任何提示将不胜感激!
请澄清一下,我如何绘制图像。我得到贝塞尔曲线路径的矩形边界和像这样裁剪的矩形图像。
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];
对于Swift 5;
func imageByApplyingClippingBezierPath(source: NSImage, path: NSBezierPath, frame: NSRect) -> NSImage? {
let new = NSImage(size: frame.size)
guard let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(frame.size.width), pixelsHigh: Int(frame.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.calibratedRGB, bitmapFormat: .alphaFirst, bytesPerRow: 0, bitsPerPixel: 0) else { return nil}
new.addRepresentation(rep)
new.lockFocus()
let context = NSGraphicsContext.current?.cgContext
context?.saveGState()
path.addClip()
let targetFrame = NSRect(x: 0, y: 0, width: Int(frame.size.width), height: Int(frame.size.height))
source.draw(in: targetFrame)
new.unlockFocus()
context?.restoreGState()
return new
}