我有一个[UIButton buttonWithType:UIButtonTypeCustom]图像(或背景图像 - 相同的问题),通过[UIImage imageWithContentsOfFile:]指向相机拍摄的JPG文件创建,并由应用程序保存在文档文件夹中.
如果我UIControlStateNormal仅定义图像,那么当我触摸按钮时,图像会像预期的那样变暗,但它也会旋转90度或180度.当我移开手指时,它恢复正常.
如果我使用相同的图像UIControlStateHighlighted,这不会发生,但后来我失去了触摸指示(较暗的图像).
这只发生在从文件中读取的图像时.它不会发生[UIImage ImageNamed:].
我尝试以PNG格式而不是JPG格式保存文件.在这种情况下,图像以错误的方向显示,并且在触摸时不会再次旋转.无论如何,这不是一个好的解决方案,因为PNG太大而且处理起来很慢.
这是一个错误还是我做错了什么?
我无法找到适当的解决方案,我需要一个快速的解决方法。下面是一个函数,给定一个 UIImage,它返回一个新图像,该图像用深色 alpha 填充变暗。上下文填充命令可以替换为其他绘制或填充例程,以提供不同类型的变暗。
这是未经优化的,并且是在对图形 api 知之甚少的情况下完成的。
您可以使用此函数来设置 UIControlStateHighlighted 状态图像,以便至少它会更暗。
+ (UIImage *)darkenedImageWithImage:(UIImage *)sourceImage
{
UIImage * darkenedImage = nil;
if (sourceImage)
{
// drawing prep
CGImageRef source = sourceImage.CGImage;
CGRect drawRect = CGRectMake(0.f,
0.f,
sourceImage.size.width,
sourceImage.size.height);
CGContextRef context = CGBitmapContextCreate(NULL,
drawRect.size.width,
drawRect.size.height,
CGImageGetBitsPerComponent(source),
CGImageGetBytesPerRow(source),
CGImageGetColorSpace(source),
CGImageGetBitmapInfo(source)
);
// draw given image and then darken fill it
CGContextDrawImage(context, drawRect, source);
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGContextSetRGBFillColor(context, 0.f, 0.f, 0.f, 0.5f);
CGContextFillRect(context, drawRect);
// get context result
CGImageRef darkened = CGBitmapContextCreateImage(context);
CGContextRelease(context);
// convert to UIImage and preserve original orientation
darkenedImage = [UIImage imageWithCGImage:darkened
scale:1.f
orientation:sourceImage.imageOrientation];
CGImageRelease(darkened);
}
return darkenedImage;
}
Run Code Online (Sandbox Code Playgroud)