UIImage裁剪出透明像素 [英] UIImage Crop Out Transparent Pixels
问题描述
在使用swift 4从UIImage裁剪透明像素之后,我需要帮助来创建完美的清晰图像.
我要创建具有去除透明色的图像,因此我使用了下面的代码.但它会模糊带有小的小方块的图像矩形出现.
I want to create image with remove transparent color, So for that i have used below code. But it blur image with small small square rectangles appears.
使用以下代码
let imageCroppedBg = imgWithClearBackgroung!.cropAlpha()
//UIImage extension
extension UIImage {
func cropAlpha() -> UIImage {
let cgImage = self.cgImage!;
let width = cgImage.width
let height = cgImage.height
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bytesPerPixel:Int = 4
let bytesPerRow = bytesPerPixel * width
let bitsPerComponent = 8
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo),
let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else {
return self
}
context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: width, height: height))
var minX = width
var minY = height
var maxX: Int = 0
var maxY: Int = 0
for x in 1 ..< width {
for y in 1 ..< height {
let i = bytesPerRow * Int(y) + bytesPerPixel * Int(x)
let a = CGFloat(ptr[i + 3]) / 255.0
if(a>0) {
if (x < minX) { minX = x };
if (x > maxX) { maxX = x };
if (y < minY) { minY = y};
if (y > maxY) { maxY = y};
}
}
}
let rect = CGRect(x: CGFloat(minX),y: CGFloat(minY), width: CGFloat(maxX-minX), height: CGFloat(maxY-minY))
let imageScale:CGFloat = self.scale
let croppedImage = self.cgImage!.cropping(to: rect)!
let ret = UIImage(cgImage: croppedImage, scale: imageScale, orientation: self.imageOrientation)
return ret;
}
}
推荐答案
在此行中检查alpha分量是否正好> 0可能不够:
Checking that the alpha component is just > zero maybe not enough in this line:
if(a>0) {
if (x < minX) { minX = x }
if (x > maxX) { maxX = x }
if (y < minY) { minY = y }
if (y > maxY) { maxY = y }
}
也许您可以将阈值设置得更高: if(a> 0.5)
甚至更高. if(a == 1)
是限制,它将保证根本不透明.
Maybe you could make the threshold higher : if(a > 0.5)
or even higher. if (a == 1)
would be the limit and it would guarantee that there is no transparency at all.
如果您想让 imageCroppedBg
的大小与 imgWithClearBackgroung
的大小相同,请设置 UIImageView
的内容模式,其中 imgWithClearBackgroung
到 .scaleAspectFit
:
If you'd like to have the imageCroppedBg
with the same size of imgWithClearBackgroung
, then set the content mode of the UIImageView
containing imgWithClearBackgroung
to .scaleAspectFit
:
let imageCroppedBg = imgWithClearBackgroung.cropAlpha()
imageView.image = imageCroppedBg
imageView.contentMode = .scaleAspectFit
有关内容模式的更多信息,请在此处a>.
For more on content modes, have a look here.
附言:在Swift中,行末尾不需要;
.
P.S: In Swift the ;
is not necessary at the end of the line.
这篇关于UIImage裁剪出透明像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!