gpt4 book ai didi

iphone - 如何使 UIImageView 变暗

转载 作者:太空狗 更新时间:2023-10-30 03:41:25 26 4
gpt4 key购买 nike

我需要在触摸 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;
}

关于iphone - 如何使 UIImageView 变暗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4006495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com