【发布时间】:2010-10-23 23:01:37
【问题描述】:
当 UIImageView 被触摸时,我需要将其变暗,几乎就像跳板上的图标(主屏幕)一样。
我应该添加 0.5 alpha 和黑色背景的 UIView。这似乎很笨拙。我应该使用图层还是其他东西(CALayers)。
【问题讨论】:
-
可以改用
UIButton吗?
标签: iphone objective-c uiimageview layer
当 UIImageView 被触摸时,我需要将其变暗,几乎就像跳板上的图标(主屏幕)一样。
我应该添加 0.5 alpha 和黑色背景的 UIView。这似乎很笨拙。我应该使用图层还是其他东西(CALayers)。
【问题讨论】:
UIButton吗?
标签: iphone objective-c uiimageview layer
我会让 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 可以有多个图像;您可以有两个版本的图像,并在需要时切换到较暗的版本。
【讨论】: