我需要将UIImageView变暗时,几乎完全像跳板(主屏幕)上的图标。如何变暗UIImageView
我应该添加UIView 0.5 alpha和黑色背景。这看起来很笨拙。我应该使用图层还是什么(CALayers)。
我需要将UIImageView变暗时,几乎完全像跳板(主屏幕)上的图标。如何变暗UIImageView
我应该添加UIView 0.5 alpha和黑色背景。这看起来很笨拙。我应该使用图层还是什么(CALayers)。
如何继承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。
有问题的UIImage恰好在UIView的子类中,所以我可以做到这一点。然而,为什么我会在drawRect方法中做到这一点,我不能直接在触摸中做到这一点吗? – 2010-10-24 00:07:38
如果是切换某个设置的问题,那么会在touchesBegan中发生。它可能会在touchesEnded中切换回来。但我认为,实际的绘图会发生在drawRect中。您可能需要结合切换状态更改,在您的UIView子类实例上调用setNeedsDisplay。 (这可能最好在自定义setter中完成。)我不确定如果UIImageView的子类如果覆盖drawRect,它的行为如何。这就是为什么我建议基本编写自己的UIImageView的'安全'方法。希望这可以帮助。 – westsider 2010-10-24 00:49:25
您误解了我的评论,为什么必须在drawRect中进行自定义绘图。为什么我不能把所有的CGContext ...代码放在touchesBegan中。 – 2010-10-24 08:11:13
UIImageView可以有多个图像;你可以有两个版本的图像,并在需要时切换到较暗的图像。
我会让一个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;
}
谢谢!这是我正在寻找的。 – VietHung 2014-03-11 16:13:55
是否可以使用“UIButton”? – 2010-10-23 23:20:54