Reputation: 622
I have a problem concerning Core Graphics drawing a shadow under my masked image.
I wrote a method to turn a grey image (actually it's an icon) into a white using a mask. Now I want to draw a shadow underneath it.
That's my code so far:
CGContextRef context = CGBitmapContextCreate(NULL, imageRect.size.width, imageRect.size.height, 8, 0, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast);
CGContextSetRGBFillColor(context, 1, 1, 1, 1);
CGContextFillRect(context, imageRect);
CGContextClipToMask(context, imageRect, image.CGImage);
CGContextSetRGBFillColor(context, 0, 0, 0, 1);
CGContextFillRect(context, imageRect);
CGImageRef bwCGImage = CGBitmapContextCreateImage(context);
UIImage *bwImage = [UIImage imageWithCGImage:bwCGImage scale:image.scale orientation:image.imageOrientation];
CGContextRelease(context);
CGImageRelease(bwCGImage);
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
[[UIColor whiteColor] set];
UIRectFill(CGRectMake(0, 0, image.size.width, image.size.height));
UIImage *normalBackgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(bwImage.CGImage), CGImageGetHeight(bwImage.CGImage), CGImageGetBitsPerComponent(bwImage.CGImage), CGImageGetBitsPerPixel(bwImage.CGImage), CGImageGetBytesPerRow(bwImage.CGImage), CGImageGetDataProvider(bwImage.CGImage), NULL, YES);
CGImageRef normalImageRef = CGImageCreateWithMask(normalBackgroundImage.CGImage, imageMask);
UIImage *normalImage = [UIImage imageWithCGImage:normalImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(imageMask);
CGImageRelease(normalImageRef);
Actually everything is working fine. Only the shadow is missing. How can I draw it?
Upvotes: 0
Views: 1847
Reputation: 36617
I always recommend the great Quartz 2D Guide by Apple. Considering your question you should read the Shadows Chapter
It includes a great demo (including comments)
void MyDrawWithShadows (CGContextRef myContext, // 1
float wd, float ht);
{
CGSize myShadowOffset = CGSizeMake (-15, 20);// 2
float myColorValues[] = {1, 0, 0, .6};// 3
CGColorRef myColor;// 4
CGColorSpaceRef myColorSpace;// 5
CGContextSaveGState(myContext);// 6
CGContextSetShadow (myContext, myShadowOffset, 5); // 7
// Your drawing code here// 8
CGContextSetRGBFillColor (myContext, 0, 1, 0, 1);
CGContextFillRect (myContext, CGRectMake (wd/3 + 75, ht/2 , wd/4, ht/4));
myColorSpace = CGColorSpaceCreateDeviceRGB ();// 9
myColor = CGColorCreate (myColorSpace, myColorValues);// 10
CGContextSetShadowWithColor (myContext, myShadowOffset, 5, myColor);// 11
// Your drawing code here// 12
CGContextSetRGBFillColor (myContext, 0, 0, 1, 1);
CGContextFillRect (myContext, CGRectMake (wd/3-75,ht/2-100,wd/4,ht/4));
CGColorRelease (myColor);// 13
CGColorSpaceRelease (myColorSpace); // 14
CGContextRestoreGState(myContext);// 15
}
Upvotes: 2