一. UIViewContentMode
lazy var image : UIImageView = {
let view = UIImageView.init(image: #imageLiteral(resourceName: "image.jpg"))
view.translatesAutoresizingMaskIntoConstraints = false;
view.backgroundColor = UIColor.gray
return view
}()
image.widthAnchor.constraint(equalToConstant: 300).isActive = true
image.heightAnchor.constraint(equalToConstant: 275).isActive = true
-
image.contentMode = .scaleToFill
縮放圖片以充滿整個(gè)容器
image.png -
image.contentMode = .scaleAspectFit
使寬或者高與容器一至,并保證圖片在容器內(nèi)完全顯示
image.png -
image.contentMode = .scaleAspectFill
使寬或者高與容器一至,超出部分被裁剪
image.png image.contentMode = .redraw
這個(gè)選項(xiàng)是當(dāng)視圖的尺寸位置發(fā)生變化的時(shí)候通過調(diào)用setNeedsDisplay方法來(lái)重新顯示。image.contentMode = .center
保持圖片原比例在視圖中間顯示圖片內(nèi)容如果視圖大小小于圖片的尺寸,則圖片會(huì)超出視圖邊界

image.png
image.contentMode = .top

image.png
以下都不會(huì)對(duì)圖片進(jìn)行放縮。而是按基準(zhǔn)對(duì)齊。圖片超出容器的部分不會(huì)被截?cái)?/p>
case center
case top
case bottom
case left
case right
case topLeft
case topRight
case bottomLeft
case bottomRight
二. 縮放,截取,壓縮
extension UIImage
{
/// 截取部分圖像
func getSubImage(rect : CGRect) -> UIImage {
guard self.cgImage != nil else {
return self
}
let croppedCGImage = self.cgImage!.cropping(to: rect)
guard croppedCGImage != nil else {
return self
}
let drawBounds = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
UIGraphicsBeginImageContext(drawBounds.size)
let currentContext = UIGraphicsGetCurrentContext()
currentContext?.draw(croppedCGImage!, in: drawBounds)
let croppedImage = UIImage(cgImage: croppedCGImage!)
UIGraphicsEndImageContext()
return croppedImage
}
/// 放縮圖片到指定尺寸
///
/// - Parameter size: 目標(biāo)尺寸
/// - Returns: 目標(biāo)UIImage
func scaleTo(size: CGSize) -> UIImage {
guard size.width >= 0 , size.height >= 0 else {
return self
}
let destinationBounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(destinationBounds.size, false, 0.0);
self.draw(in: destinationBounds)
let destinationImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
guard destinationImage != nil else {
return self
}
return destinationImage!
}
/// 按比例縮放圖片
///
/// - Parameter radio: 縮放比例
/// - Returns: 縮放后的UIImage
func scaleRadio(radio:CGFloat) -> UIImage {
guard radio > 0 else {
return self
}
guard self.cgImage != nil else {
return self
}
let resultImage = UIImage.init(cgImage: self.cgImage!, scale: radio, orientation: self.imageOrientation)
return resultImage
}
/**
聽說某司用的就是這一壓縮算法
圖片壓縮的邏輯:
一:圖片尺寸壓縮 主要分為以下幾種情況 一般參照像素為targetPx
a.圖片寬高均≤targetPx時(shí),圖片尺寸保持不變;
b.寬或高均>targetPx時(shí) ——圖片寬高比≤2,則將圖片寬或者高取大的等比壓縮至targetPx; ——但是圖片寬高比>2時(shí),則寬或者高取小的等比壓縮至targetPx;
c.寬高一個(gè)>targetPx,另一個(gè)<targetPx,--圖片寬高比>2時(shí),則寬高尺寸不變;--但是圖片寬高比≤2時(shí),則將圖片寬或者高取大的等比壓縮至targetPx.
二:圖片質(zhì)量壓縮: 對(duì)于超過大小閾值的圖片進(jìn)行質(zhì)量壓縮,但不保證壓縮后的大小
一般圖片質(zhì)量都?jí)嚎s在90%就可以了
*/
func conpressImageView(targetPx:CGFloat, thresholdSize_KB:Int = 200)->Data?
{
var newImage:UIImage! // 尺寸壓縮后的新圖片
let imageSize:CGSize = self.size // 源圖片的size
let width:CGFloat = imageSize.width // 源圖片的寬
let height:CGFloat = imageSize.height // 原圖片的高
var drawImge:Bool = false // 是否需要重繪圖片 默認(rèn)是NO
var scaleFactor:CGFloat = 0.0 // 壓縮比例
var scaledWidth:CGFloat = targetPx // 壓縮時(shí)的寬度 默認(rèn)是參照像素
var scaledHeight:CGFloat = targetPx // 壓縮是的高度 默認(rèn)是參照像素
if width <= targetPx,height <= targetPx {
newImage = self
}
else if width >= targetPx , height >= targetPx {
drawImge = true
let factor:CGFloat = width / height
if factor <= 2 {
// b.1圖片寬高比≤2,則將圖片寬或者高取大的等比壓縮至targetPx
scaleFactor = width > height ? targetPx/width : targetPx/height
} else {
// b.2圖片寬高比>2時(shí),則寬或者高取小的等比壓縮至targetPx
scaleFactor = width > height ? targetPx/height : targetPx/width
}
}
// c.寬高一個(gè)>targetPx,另一個(gè)<targetPx 寬大于targetPx
else if width >= targetPx , height <= targetPx {
if width / height > 2 {
newImage = self;
} else {
drawImge = true;
scaleFactor = targetPx / width;
}
}
// c.寬高一個(gè)>targetPx,另一個(gè)<targetPx 高大于targetPx
else if width <= targetPx , height >= targetPx {
if height / width > 2 {
newImage = self;
} else {
drawImge = true;
scaleFactor = targetPx / height;
}
}
// 如果圖片需要重繪 就按照新的寬高壓縮重繪圖片
if drawImge {
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
UIGraphicsBeginImageContext(CGSize(width:scaledWidth,height:scaledHeight));
// 繪制改變大小的圖片
self.draw(in: CGRect.init(x: 0, y: 0, width: scaledWidth, height: scaledHeight))
// 從當(dāng)前context中創(chuàng)建一個(gè)改變大小后的圖片
newImage = UIGraphicsGetImageFromCurrentImageContext();
// 使當(dāng)前的context出堆棧
UIGraphicsEndImageContext();
}
// 如果圖片大小大于200kb 在進(jìn)行質(zhì)量上壓縮
var scaledImageData:Data? = nil;
guard newImage != nil else {
return nil;
}
if (UIImageJPEGRepresentation(newImage!, 1) == nil) {
scaledImageData = UIImagePNGRepresentation(newImage);
}else{
scaledImageData = UIImageJPEGRepresentation(newImage, 1);
guard scaledImageData != nil else {
return nil
}
if scaledImageData!.count >= 1024 * thresholdSize_KB {
//壓縮大小,但并不一定能一次到位,有需有可以for循環(huán)壓縮
//scaledImageData > 1024 * thresholdSize_KB
scaledImageData = UIImageJPEGRepresentation(newImage, 0.9);
}
}
return scaledImageData
}
}
三. text、view、color To Image
/// 創(chuàng)建純色圖片
///
/// - Parameters:
/// - color: 圖片顏色
/// - size: 圖片的大小
/// - Returns: 純色圖片UIImage
static func colorImage(color : UIColor, size : CGSize ) -> UIImage? {
let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(size)
let currentContext = UIGraphicsGetCurrentContext()
currentContext?.setFillColor(color.cgColor)
currentContext?.fill(bounds)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
return resultImage!
}
/// 文本轉(zhuǎn)圖片
///
/// - Parameters:
/// - text: 文本
/// - attribute: 文本富文本屬性
/// - size: 圖片大小
/// - Returns: UIImage
static func textImage(text:NSString, attribute:Dictionary<String, Any>?, size:CGSize) -> UIImage?
{
let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
text.draw(in: bounds, withAttributes: attribute)
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage
}
/// 將View轉(zhuǎn)換成圖片
///
/// - Parameter view: 需要轉(zhuǎn)換的View
/// - Returns: UIImage
static func viewImage(view : UIView) -> UIImage?
{
view.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
if view.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:))) {
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}
else{
let currentContext = UIGraphicsGetCurrentContext()
guard currentContext != nil else {
return nil
}
view.layer.render(in: currentContext!)
}
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage
}


