Skip to content

Instantly share code, notes, and snippets.

@orklann
Last active June 12, 2018 06:46
Show Gist options
  • Select an option

  • Save orklann/dfc05e68caf37372d6dc to your computer and use it in GitHub Desktop.

Select an option

Save orklann/dfc05e68caf37372d6dc to your computer and use it in GitHub Desktop.
Draw NSImage onto another NSImage (Better)
@interface NSImage (NSBitmapImageRep)
- (NSBitmapImageRep *)bitmapImageRepresentation;
@end
@implementation NSImage (NSBitmapImageRep)
- (NSBitmapImageRep *)bitmapImageRepresentation
{
int width = [self size].width;
int height = [self size].height;
if(width < 1 || height < 1)
return nil;
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes: NULL
pixelsWide: width
pixelsHigh: height
bitsPerSample: 8
samplesPerPixel: 4
hasAlpha: YES
isPlanar: NO
colorSpaceName: NSDeviceRGBColorSpace
bytesPerRow: width * 4
bitsPerPixel: 32];
NSGraphicsContext *ctx = [NSGraphicsContext graphicsContextWithBitmapImageRep: rep];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext: ctx];
[self drawAtPoint: NSZeroPoint fromRect: NSZeroRect operation: NSCompositeCopy fraction: 1.0];
[ctx flushGraphics];
[NSGraphicsContext restoreGraphicsState];
return rep;
//CGImageRef CGImage = [self CGImageForProposedRect:nil context:nil hints:nil];
//return [[NSBitmapImageRep alloc] initWithCGImage:CGImage];
}
@end
// Draw NSImage onto NSImage at position p
// Ugly but works, will use it and improve it in next project
// by using objc category or something like that.
// Why this?
// This code is better than [NSImage lock] and [NSImage unlock], because it will not produce x2 large png
// bug while some retina external displays connected.
void drawImageToImage(NSImage *srcImage, NSImage *destImage, NSPoint p) {
NSBitmapImageRep *rep = [destImage bitmapImageRepresentation];
if (rep == nil) {
NSLog(@"Rep is nil");
}
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext *ctx = [NSGraphicsContext graphicsContextWithBitmapImageRep: rep];
[NSGraphicsContext setCurrentContext:ctx];
// Drawing
[srcImage drawAtPoint:p
fromRect:NSZeroRect
operation:NSCompositeSourceOver
fraction:1.0];
// End drawing
[ctx flushGraphics];
[NSGraphicsContext restoreGraphicsState];
// For test purpose
//NSData *data = [rep representationUsingType:NSPNGFileType properties:Nil];
//[data writeToFile: @"/Users/aaron/Desktop/test.png" atomically: NO];
return [[NSImage alloc] initWithCGImage:[rep CGImage] size:NSZeroSize];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment