1

我正在尝试为图像添加一个小阴影,就像 App Store 中的图标阴影一样。现在我正在使用以下代码来圆角我的图像。有谁知道我如何调整它来添加一个小阴影?

- (UIImage *)roundCornersOfImage:(UIImage *)source height:(int)height width:(int)width  {
    int w = width;
    int h = height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef imageContext = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);

    CGContextBeginPath(imageContext);

    CGRect rect = CGRectMake(0, 0, w, h);
    addRoundedRectToPath(imageContext, rect, 10, 10);
    CGContextClosePath(imageContext);
    CGContextClip(imageContext);

    CGContextDrawImage(imageContext, CGRectMake(0, 0, w, h), source.CGImage);

    CGImageRef imageMasked = CGBitmapContextCreateImage(imageContext);
    CGContextRelease(imageContext);
    CGColorSpaceRelease(colorSpace);
    
    return [UIImage imageWithCGImage:imageMasked];    
}

addRoundedRectToPath指的是另一种明显圆角的方法。

4

1 回答 1

6

首先,这是文档的链接:

http://developer.apple.com/iPhone/library/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadows/dq_shadows.html#//apple_ref/doc/uid/TP30001066-CH208-TPXREF101

接下来,尝试在调用 CGContextDrawImage(...) 之前添加类似这样的内容:

CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
CGColorRef shadowColor = CGColorCreate(colorSpace, components);
CGContextSetShadowWithColor(imageContext, CGSizeMake(3, 3), 2, shadowColor);
CGColorRelease(shadowColor);

之后,对 CGContextSetShadowWithColor(.....) 的调用,所有内容都应该使用偏移 (3, 3) 点的阴影绘制,并使用 2.0 点模糊半径绘制。您可能需要调整黑色的不透明度(组件中的第四个组件),并更改阴影参数。

如果你想在某个时候停止绘制阴影,你需要在调用 CGContextSetShadowWithColor 之前保存图形上下文,并在你想停止绘制阴影时恢复它。

于 2009-06-07T23:36:18.963 回答