我有一个问题,关于Core Graphics在我的蒙面图像下画一个阴影。
我写了一个方法,使用蒙版将灰色图像(实际上是图标)变成白色。现在我想在它下面画一个阴影。
到目前为止,这是我的代码:
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);
实际上一切都运转良好。只有阴影丢失了。我怎么画它?
答案 0 :(得分:2)
我总是推荐Apple出色的Quartz 2D Guide。考虑到您的问题,您应该阅读Shadows Chapter
它包括一个很棒的演示(包括评论)
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
}