最近项目完成的差不多了,也想记录一写东西。从开始慢慢整理吧。
先记录一下项目中记忆点最深的一个地方 。先上效果图。
这个需求看起来简单吧?当时搞到了12点多。完成思路两点:
1、生成透明底的二维码image;
//生成二维码
class func creatQRCodeImage(text: String, WH: CGFloat) -> UIImage{
//创建滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
//还原滤镜的默认属性
filter?.setDefaults()
//设置需要生成二维码的数据
filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
//从滤镜中取出生成的图片
let ciImage = filter?.outputImage
//这个清晰度好
let bgImage = createNonInterpolatedUIImageFormCIImage(image: ciImage!, size: WH)
return bgImage
}
class func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
let extent: CGRect = image.extent.integral
let scale: CGFloat = min(size/extent.width * 2, size/extent.height * 2)
let width = extent.width * scale
let height = extent.height * scale
let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)!
let context = CIContext(options: nil)
let bitmapImage: CGImage = context.createCGImage(image, from: extent)!
bitmapRef.interpolationQuality = CGInterpolationQuality.none
bitmapRef.scaleBy(x: scale, y: scale)
bitmapRef.draw(bitmapImage, in: extent)
let scaledImage: CGImage = bitmapRef.makeImage()!
return UIImage(cgImage: scaledImage)
}
extension UIImage {
//返回一个将白色背景变透明的UIImage
func imageByRemoveWhiteBg() -> UIImage? {
let colorMasking: [CGFloat] = [222, 255, 222, 255, 222, 255]
return transparentColor(colorMasking: colorMasking)
}
func transparentColor(colorMasking:[CGFloat]) -> UIImage? {
if let rawImageRef = self.cgImage {
UIGraphicsBeginImageContext(self.size)
if let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking) {
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translateBy(x: 0.0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.draw(maskedImageRef, in: CGRect(x:0, y:0, width:self.size.width, height:self.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
return nil
}
}
2、将imageView旋转压缩;
压缩这里的思路是将QRImageView先截图再旋转再上下压缩height为1/2就好,这里贴上将view->UIImage就好;
extension UIView {
//将当前视图转为UIImage
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext)
}
}
}