2010-10-23 81 views
6

我需要將UIImageView變暗時,幾乎完全像跳板(主屏幕)上的圖標。如何變暗UIImageView

我應該添加UIView 0.5 alpha和黑色背景。這看起來很笨拙。我應該使用圖層還是什麼(CALayers)。

+0

是否可以使用「UIButton」? – 2010-10-23 23:20:54

回答

4

如何繼承UIView並添加UIImage伊娃(稱爲圖像)?然後你可以重寫-drawRect:類似這樣的事情,只要你有一個叫做按下的布爾型伊娃就是在觸摸時設置的。

- (void)drawRect:(CGRect)rect 
{ 
[image drawAtPoint:(CGPointMake(0.0, 0.0))]; 

// if pressed, fill rect with dark translucent color 
if (pressed) 
    { 
    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(ctx); 
    CGContextSetRGBFillColor(ctx, 0.5, 0.5, 0.5, 0.5); 
    CGContextFillRect(ctx, rect); 
    CGContextRestoreGState(ctx); 
    } 
} 

你會想要試驗上面的RGBA值。當然,非矩形形狀需要更多的工作 - 比如CGMutablePathRef。

+1

有問題的UIImage恰好在UIView的子類中,所以我可以做到這一點。然而,爲什麼我會在drawRect方法中做到這一點,我不能直接在觸摸中做到這一點嗎? – 2010-10-24 00:07:38

+0

如果是切換某個設置的問題,那麼會在touchesBegan中發生。它可能會在touchesEnded中切換回來。但我認爲,實際的繪圖會發生在drawRect中。您可能需要結合切換狀態更改,在您的UIView子類實例上調用setNeedsDisplay。 (這可能最好在自定義setter中完成。)我不確定如果UIImageView的子類如果覆蓋drawRect,它的行爲如何。這就是爲什麼我建議基本編寫自己的UIImageView的'安全'方法。希望這可以幫助。 – westsider 2010-10-24 00:49:25

+0

您誤解了我的評論,爲什麼必須在drawRect中進行自定義繪圖。爲什麼我不能把所有的CGContext ...代碼放在touchesBegan中。 – 2010-10-24 08:11:13

1

UIImageView可以有多個圖像;你可以有兩個版本的圖像,並在需要時切換到較暗的圖像。

6

我會讓一個UIImageView處理圖像的實際繪製,但切換圖像到一個事先變暗的圖像。以下是我用來生成暗淡圖像的一些代碼,其中保留了alpha:

+ (UIImage *)darkenImage:(UIImage *)image toLevel:(CGFloat)level 
{ 
    // Create a temporary view to act as a darkening layer 
    CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); 
    UIView *tempView = [[UIView alloc] initWithFrame:frame]; 
    tempView.backgroundColor = [UIColor blackColor]; 
    tempView.alpha = level; 

    // Draw the image into a new graphics context 
    UIGraphicsBeginImageContext(frame.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [image drawInRect:frame]; 

    // Flip the context vertically so we can draw the dark layer via a mask that 
    // aligns with the image's alpha pixels (Quartz uses flipped coordinates) 
    CGContextTranslateCTM(context, 0, frame.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    CGContextClipToMask(context, frame, image.CGImage); 
    [tempView.layer renderInContext:context]; 

    // Produce a new image from this context 
    CGImageRef imageRef = CGBitmapContextCreateImage(context); 
    UIImage *toReturn = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef); 
    UIGraphicsEndImageContext(); 
    [tempView release]; 
    return toReturn; 
} 
+0

謝謝!這是我正在尋找的。 – VietHung 2014-03-11 16:13:55