当UIImageView被触摸时,我需要将其变暗,就像SpringBoard(主屏幕)上的图标一样。
我应该添加一个alpha为0.5且背景为黑色的UIView。这似乎很笨拙。我应该使用图层或类似的东西吗(CALayers)。
当UIImageView被触摸时,我需要将其变暗,就像SpringBoard(主屏幕)上的图标一样。
我应该添加一个alpha为0.5且背景为黑色的UIView。这似乎很笨拙。我应该使用图层或类似的东西吗(CALayers)。
我会让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;
}
- (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);
}
}
UIImageView 可以拥有多个图片;当需要时,你可以切换到较暗的版本。
UIButton
吗? - John Calsbeek