I have been programming for two years on iOS and never on mac. I am working on a little utility for handling some simple image needs that I have in my iOS development. Anyway, I have working code in iOS that runs perfectly but I have absolutely no idea what equivalents are for mac.
I've tried a bunch of different things but I really don't understand how to start a graphics context on the Mac outside of a "drawRect:" method. On the iPhone I would just use UIGraphicsBeghinImageContext(). I know other post have said to use lockFocus/unlockFocus but I'm not sure how exactly to make that work for my needs. Oh, and I really miss UIImage's "CGImage" property. I don't understand why NSImage can't have one, though it sounds a bit trickier than just that.
Here is my working code on iOS—basically it just creates a reflected image from a mask and combines them together:
UIImage *mask = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Mask_Image.jpg" ofType:nil]];
UIImage *image = [UIImage imageNamed::@"Test_Image1.jpg"];
UIGraphicsBeginImageContextWithOptions(mask.size, NO, [[UIScreen mainScreen]scale]);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0.0, mask.size.height);
CGContextScaleCTM(ctx, 1.f, -1.f);
[image drawInRect:CGRectMake(0.f, -mask.size.height, image.size.width, image.size.height)];
UIImage *flippedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef maskRef = mask.CGImage;
CGImageRef maskCreate = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([flippedImage CGImage], maskCreate);
CGImageRelease(maskCreate);
UIImage *maskedImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width, image.size.height + (image.size.height * .5)), NO, [[UIScreen mainScreen]scale]);
[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];
[maskedImage drawInRect:CGRectMake(0, image.size.height, maskedImage.size.width, maskedImage.size.height)];
UIImage *anotherImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//do something with anotherImage
Any suggestions for achieving this (simply) on the Mac?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…