UIButton的图像旋转问题
问题描述:
我有一个[UIButton buttonWithType:UIButtonTypeCustom]
具有图像(或背景图片 - 同样的问题)由[UIImage imageWithContentsOfFile:]
指向创建相机应用程序拍摄并保存在文档文件夹中的JPG文件。UIButton的图像旋转问题
如果我只为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;
}
答
要解决这个问题,你需要额外的标准化功能是这样的:在那里设置解开背景后
self.photoButton.sd_setImageWithURL(avatarURL,
forState: .Normal,
placeholderImage: UIImage(named: "user_avatar_placeholder")) {
[weak self] (image, error, cacheType, url) in
guard let strongSelf = self else {
return
}
strongSelf.photoButton.setImage(image.normalizedImage(), forState: .Normal
}
我有一个类似的问题:
那么你可以使用它像图像到从uiimagepicker选择的图片,图像显示旋转90度。 – marciokoko