[英]UIGraphicsGetImageFromCurrentImageContext counterpart in desktop Cocoa?
我正在尝试创建一个简单的Mac绘图应用程序。 在iOS上,我使用UIGraphicsGetImageFromCurrentImageContext在touchesMoved时更新UIImageView的图像。 我现在正试图激活同样的东西,但在Mac应用程序上,我想做:
myNSImageView.image = UIGraphicsGetImageFromCurrentImageContext();
但是这个函数只存在于cocoa-touch而不存在于cocoa框架中,关于在Cocoa中可以找到类似函数的地方的任何提示?
谢谢。
更新
一些额外的完整性代码。
- (void)mouseDragged:(NSEvent *)event
{
NSInteger width = canvasView.frame.size.width;
NSInteger height = canvasView.frame.size.height;
NSGraphicsContext * graphicsContext = [NSGraphicsContext currentContext];
CGContextRef contextRef = (CGContextRef) [graphicsContext graphicsPort];
CGContextRef imageContextRef = CGBitmapContextCreate(0, width, height, 8, width*4, [NSColorSpace genericRGBColorSpace].CGColorSpace, kCGImageAlphaPremultipliedFirst);
NSPoint currentPoint = [event locationInWindow];
CGContextSetRGBStrokeColor(contextRef, 49.0/255.0, 147.0/255.0, 239.0/255.0, 1.0);
CGContextSetLineWidth(contextRef, 1.0);
CGContextBeginPath(contextRef);
CGContextMoveToPoint(contextRef, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(contextRef, currentPoint.x, currentPoint.y);
CGContextDrawPath(contextRef,kCGPathStroke);
CGImageRef imageRef = CGBitmapContextCreateImage(imageContextRef);
NSImage* image = [[NSImage alloc] initWithCGImage:imageRef size:NSMakeSize(width, height)];
canvasView.image = image;
CFRelease(imageRef);
CFRelease(imageContextRef);
lastPoint = currentPoint;
}
我现在得到的结果是,这幅画在视图的上半部分工作正常,但其余部分则是僵尸。 就像在这个图像上(红色部分应该是canvasView):
NSInteger width = 1024;
NSInteger height = 768;
CGContextRef contextRef = CGBitmapContextCreate(0, width, height, 8, width*4, [NSColorSpace genericRGBColorSpace].CGColorSpace, kCGImageAlphaPremultipliedFirst);
CGContextSetRGBStrokeColor(contextRef, 49.0/255.0, 147.0/255.0, 239.0/255.0, 1.0);
CGContextFillRect(contextRef, CGRectMake(0.0f, 0.0f, width, height));
CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
NSImage* image = [[NSImage alloc] initWithCGImage:imageRef size:NSMakeSize(width, height)];
CFRelease(imageRef);
CFRelease(contextRef);
NSGraphicsContext * graphicsContext = [NSGraphicsContext currentContext]; CGContextRef contextRef = (CGContextRef) [graphicsContext graphicsPort]; CGContextRef imageContextRef = CGBitmapContextCreate(0, width, height, 8, width*4, [NSColorSpace genericRGBColorSpace].CGColorSpace, kCGImageAlphaPremultipliedFirst);
首先,假设存在当前上下文,然后创建单独的上下文。
CGContextSetRGBStrokeColor(contextRef, 49.0/255.0, 147.0/255.0, 239.0/255.0, 1.0); CGContextSetLineWidth(contextRef, 1.0); (etc.)
然后,您将绘制到您认为存在的上下文,而不是您创建的上下文。
CGImageRef imageRef = CGBitmapContextCreateImage(imageContextRef);
然后根据您创建的上下文创建一个图像,从不插入。
切出尝试获取[NSGraphicsContext currentContext]
及其图形端口。 无论如何,您不能假设drawRect:
之外存在当前上下文。 相反,请绘制您创建的上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.