2010-10-23 4 views
6

UIImageView를 터치하면 어두워 져야합니다. 거의은 스프링 보드 (홈 스크린)의 아이콘과 같습니다.UIImageView를 어둡게하는 방법

0.5 알파와 검은 색 배경으로 UIView를 추가해야합니까? 이것은 서투른 것처럼 보인다. 레이어 또는 무언가를 사용해야합니까 (CALayers).

+0

대신 'UIButton'을 사용할 수 있습니까? –

답변

4

UIView를 서브 클래 싱하고 UIImage ivar (이미지라고 함)를 추가하는 것은 어떻습니까? 그런 다음 당신은 -drawRect를 오버라이드 할 수 있습니다 : 터치 한 상태에서 설정 한 눌려진 부울 ivar를 제공했다면, 이와 비슷한 것입니다.

- (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는 이미 UIct 하위 클래스에 있으므로이 작업을 수행 할 수 있습니다. 그러나 drawRect 메서드에서이 작업을 수행하는 이유는 직접 터치를 시작할 수 없기 때문입니다. –

+0

일부 설정을 전환하는 문제라면 touchesBegan에서 발생할 수 있습니다. 그리고 그것은 touchesEnded에서 다시 토글 될 수 있습니다. 그러나 실제 드로잉은 drawRect에서 발생한다고 생각합니다. 토글 된 상태 변경과 함께 UIView 하위 클래스 인스턴스에서 setNeedsDisplay를 호출해야 할 수도 있습니다. (이것은 사용자 정의 설정자에서 가장 잘 수행 될 수 있습니다.) drawRect가 재정의 된 경우 UIImageView의 하위 클래스가 어떻게 작동하는지 잘 모르겠습니다. 이것이 내가 기본적으로 자신의 UIImageView를 작성하는 '보다 안전한'접근 방식을 제안한 이유입니다. 희망이 도움이됩니다. – westsider

+0

당신이 내 의견을 오해 한 것입니다. 왜 drawRect에서 사용자 지정 그리기가 발생해야합니까? 왜 모든 CGContext ... touchesBegan에 코드를 넣을 수 없습니까? –

1

UIImageView는 여러 개의 이미지를 가질 수 있습니다. 필요한 경우 두 가지 버전의 이미지를 가지고 더 어두운 이미지로 전환 할 수 있습니다.

6

저는 UIImageView가 이미지의 실제 그림을 처리하도록하지만, 미리 이미지가 어두워 졌는지를 토글합니다. 다음은 알파가 유지 된 어두운 이미지를 생성하는 데 사용한 코드입니다.

+ (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

관련 문제