UIImage

一. 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

  1. image.contentMode = .scaleToFill
    縮放圖片以充滿整個(gè)容器

    image.png

  2. image.contentMode = .scaleAspectFit
    使寬或者高與容器一至,并保證圖片在容器內(nèi)完全顯示

    image.png

  3. image.contentMode = .scaleAspectFill
    使寬或者高與容器一至,超出部分被裁剪

    image.png

  4. image.contentMode = .redraw
    這個(gè)選項(xiàng)是當(dāng)視圖的尺寸位置發(fā)生變化的時(shí)候通過調(diào)用setNeedsDisplay方法來(lái)重新顯示。

  5. image.contentMode = .center

保持圖片原比例在視圖中間顯示圖片內(nèi)容如果視圖大小小于圖片的尺寸,則圖片會(huì)超出視圖邊界


image.png
  1. 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
    }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 官方文檔點(diǎn)藍(lán)色文字:UIImage、CIImage、CGImage。 這篇文章是對(duì)官方文檔的學(xué)習(xí)筆記,不是翻譯,對(duì)...
    阿斯蘭iOS閱讀 6,721評(píng)論 1 8
  • 在給view 添加背景圖片的時(shí)候,發(fā)現(xiàn)view 沒有 contents模式,這樣在給view添加背景圖時(shí)就變?cè)斐衫?..
    twttt閱讀 403評(píng)論 0 0
  • 繼基礎(chǔ)控件UITextView之后,期待的UIImageView,UIImage詳細(xì)介紹-->>保證你有意外收獲,...
    MrBrave丶彬彬閱讀 3,364評(píng)論 0 2
  • Never be afraid of the moments--thus sings the voice of t...
    我是嗚嗚閱讀 308評(píng)論 0 0
  • 前段時(shí)間,聽了阿何的網(wǎng)絡(luò)課程《引爆你的學(xué)習(xí)力》,里面提到了一種學(xué)習(xí)方法叫“三步式快速學(xué)習(xí)法”,已經(jīng)嘗試著用了一段時(shí)...
    w王大銘閱讀 1,336評(píng)論 0 2

友情鏈接更多精彩內(nèi)容