UIImage裁剪出透明像素

时间:2018-08-20 09:24:43

标签: ios swift uiimage core-graphics crop

在使用swift 4从UIImage裁剪透明像素之后,我需要帮助来创建完美的清晰图像。

  

我要创建带有透明色的图像,因此我   使用下面的代码。但是它会模糊带有小方块的图像   矩形出现。

使用以下代码

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;
    }
}

Output blurred & small square in small

Image with Alpha/transparent pixel

1 个答案:

答案 0 :(得分:0)

在此行中检查alpha分量是否> 0可能不够:

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)是极限,它将保证根本不透明。

如果您想让imageCroppedBg的大小与imgWithClearBackgroung相同,则将包含UIImageView的{​​{1}}的内容模式设置为{{1} }:

imgWithClearBackgroung

有关内容模式的更多信息,请查看here

PS::在Swift中,.scaleAspectFit在行的末尾不是必需的。