我有一个 PNG 图像文件,我正在使用 UIImageView 在视图中显示图像。我想将图像中的白色更改为透明。
注意:我的父视图颜色可以是不同的颜色。(不只是白色)
这是我的代码:
UIImageView* oriImageView = [[UIImageView alloc]initWithFrame:originalFrame];
UIImage* oriImage = [UIImage imageNamed:@"tap.png"];
oriImageView.layer.opacity = 0.5f;
oriImageView.backgroundColor = [UIColor clearColor];
oriImageView.opaque = NO;
oriImageView.tintColor = [UIColor clearColor];
oriImageView.image = oriImage;
[self.view addSubview:oriImageView];
Run Code Online (Sandbox Code Playgroud)
我尝试了以下不同的选项,但没有成功。
oriImageView.backgroundColor = [UIColor clearColor];
oriImageView.opaque = NO;
oriImageView.tintColor = [UIColor clearColor];
Run Code Online (Sandbox Code Playgroud)
当您的背景颜色为白色时,此代码将起作用,根据您的需要更改颜色值
extension UIImage {
func imageByMakingWhiteBackgroundTransparent() -> UIImage? {
let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
let rawImageRef: CGImage = image.cgImage!
let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
UIGraphicsBeginImageContext(image.size);
let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1826 次 |
| 最近记录: |