Iphone 如何使UIImageView变暗
我需要在触摸UIImageView时将其变暗,几乎与springboard(主屏幕)上的图标完全相同Iphone 如何使UIImageView变暗,iphone,objective-c,uiimageview,layer,Iphone,Objective C,Uiimageview,Layer,我需要在触摸UIImageView时将其变暗,几乎与springboard(主屏幕)上的图标完全相同 我应该添加0.5 alpha和黑色背景的UIView。这似乎很笨拙。我应该使用图层或其他东西(CALayers)。UIImageView可以有多个图像;您可以有两个版本的图像,并在需要时切换到较暗的版本。将UIView子类化并添加UIImage ivar(称为图像)如何?然后,您可以覆盖-drawRect:类似这样的内容,前提是您有一个名为pressed的布尔ivar,它是在触摸时设置的 - (
我应该添加0.5 alpha和黑色背景的UIView。这似乎很笨拙。我应该使用图层或其他东西(CALayers)。UIImageView可以有多个图像;您可以有两个版本的图像,并在需要时切换到较暗的版本。将UIView子类化并添加UIImage ivar(称为图像)如何?然后,您可以覆盖-drawRect:类似这样的内容,前提是您有一个名为pressed的布尔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处理图像的实际绘制,但会将图像切换到预先变暗的图像。下面是一些代码,我使用这些代码生成带有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;
}
是否可以改用
ui按钮
?问题中的UIImage碰巧已经在子类UIView中,所以我可以这样做。然而,为什么我要在drawRect方法中执行此操作,我不能直接在Touchs Start中执行此操作吗?如果这是切换某些设置的问题,那么这将发生在Touchs Start中。它可能会在touchSended中切换回来。但我认为,实际的绘图将发生在drawRect中。您可能需要在UIView子类实例上调用setNeedsDisplay,同时进行切换状态更改。(这最好在custom setter中完成。)我不确定UIImageView的子类在其drawRect被重写时的行为。这就是为什么我建议使用“更安全”的方法来编写自己的UIImageView。希望这有帮助。您误解了我的评论,为什么自定义绘图必须在drawRect中进行。为什么我不能把所有的背景。。。触摸中的代码开始了。@Jonathan,引用Joe Conway和Aaron Hillegass在他们的书《iPhone编程:大书呆子牧场指南》第91页中的话,“drawRect:方法是视图的绘图代码所在。”我总是在drawRect:中绘制核心图形。您可能需要通读这篇文章以了解更多详细信息。我找不到警告不要在drawRect之外绘图的文档:;我想我读过类似的东西…谢谢!这就是我要找的。