swift 的UIImage + Helper.swift
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 的UIImage + Helper.swift相关的知识,希望对你有一定的参考价值。
import UIKit
extension UIImageView {
convenience init(image: UIImage?,contentMode: UIView.ContentMode?, cornerRadius: CGFloat? = 0, userInteraction: Bool? = false) {
self.init(frame: .zero)
if let image = image {
self.image = image
}
if let contentMode = contentMode {
self.contentMode = contentMode
}
if let cornerRadius = cornerRadius {
self.clipsToBounds = true
self.layer.cornerRadius = cornerRadius
}
if let userInteraction = userInteraction {
self.isUserInteractionEnabled = userInteraction
}
}
}
extension UIImage {
func resizeWithCGsize(scaledToSize newSize:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
func maskWithColor(color: UIColor) -> UIImage? {
let maskImage = cgImage!
let width = size.width
let height = size.height
let bounds = CGRect(x: 0, y: 0, width: width, height: height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
context.clip(to: bounds, mask: maskImage)
context.setFillColor(color.cgColor)
context.fill(bounds)
if let cgImage = context.makeImage() {
let coloredImage = UIImage(cgImage: cgImage)
return coloredImage
} else {
return nil
}
}
}
以上是关于swift 的UIImage + Helper.swift的主要内容,如果未能解决你的问题,请参考以下文章
将 UIImage 转换为 NSData 并在 Swift 中转换回 UIImage?
Swift:如何从 UIImage 数组中提取图像文件名
将UIImage转换为NSData并在Swift中转换回UIImage?
swift 的UIImage + Helper.swift
swift 的UIImage +色调+ Resize.swift
如何在 Swift 中为 UIImage 着色?