2009-06-07 217 views
1

我試圖給圖像添加一個小陰影,很像App Store中的圖標陰影。現在我正在使用下面的代碼繞過我的圖像的角落。有誰知道我可以如何調整它來增加一個小影子?UIImage Shadow Trouble

- (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」指的是另一種明顯四捨五入的方法。

回答

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之前保存圖形上下文,並在您想要停止使用陰影進行繪製時將其恢復。

+2

CGContextSetShadowWithColor的參數2是CGSize。因此它應該是CGContextSetShadowWithColor(imageContext,CGSizeMake(3,3),2,shadowColor); – samvermette 2010-05-28 20:38:47