我需要在 UIImageView 被触摸时使其变暗,几乎就像跳板上的图标(主屏幕)一样。
我应该添加 0.5 alpha 和黑色背景的 UIView。这似乎很笨拙。我应该使用图层还是其他东西(CALayers)。
我需要在 UIImageView 被触摸时使其变暗,几乎就像跳板上的图标(主屏幕)一样。
我应该添加 0.5 alpha 和黑色背景的 UIView。这似乎很笨拙。我应该使用图层还是其他东西(CALayers)。
我会让 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;
}
子类化 UIView 并添加 UIImage ivar(称为图像)怎么样?然后你可以覆盖 -drawRect: 类似这样的东西,前提是你有一个名为 press 的布尔 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。
UIImageView 可以有多个图像;您可以拥有两个版本的图像,并在需要时切换到较暗的版本。