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
    缩放图片以充满整个容器

    image.png

  2. image.contentMode = .scaleAspectFit
    使宽或者高与容器一至,并保证图片在容器内完全显示

    image.png

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

    image.png

  4. image.contentMode = .redraw
    这个选项是当视图的尺寸位置发生变化的时候通过调用setNeedsDisplay方法来重新显示。

  5. image.contentMode = .center

保持图片原比例在视图中间显示图片内容如果视图大小小于图片的尺寸,则图片会超出视图边界


image.png
  1. image.contentMode = .top
image.png

以下都不会对图片进行放缩。而是按基准对齐。图片超出容器的部分不会被截断

    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: 目标尺寸
    /// - Returns: 目标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时,图片尺寸保持不变;
     b.宽或高均>targetPx时 ——图片宽高比≤2,则将图片宽或者高取大的等比压缩至targetPx; ——但是图片宽高比>2时,则宽或者高取小的等比压缩至targetPx;
     c.宽高一个>targetPx,另一个<targetPx,--图片宽高比>2时,则宽高尺寸不变;--但是图片宽高比≤2时,则将图片宽或者高取大的等比压缩至targetPx.
     
     二:图片质量压缩: 对于超过大小阈值的图片进行质量压缩,但不保证压缩后的大小
     一般图片质量都压缩在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    // 是否需要重绘图片 默认是NO
        var scaleFactor:CGFloat = 0.0   // 压缩比例
        var scaledWidth:CGFloat = targetPx   // 压缩时的宽度 默认是参照像素
        var scaledHeight:CGFloat = targetPx  // 压缩是的高度 默认是参照像素
        
        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时,则宽或者高取小的等比压缩至targetPx
                scaleFactor = width > height ? targetPx/height : targetPx/width
            }
            
        }
            // c.宽高一个>targetPx,另一个<targetPx 宽大于targetPx
        else if width >= targetPx , height <= targetPx {
            if width / height > 2 {
                newImage = self;
            } else {
                drawImge = true;
                scaleFactor = targetPx / width;
            }
        }
            // c.宽高一个>targetPx,另一个<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))
            // 从当前context中创建一个改变大小后的图片
            newImage = UIGraphicsGetImageFromCurrentImageContext();
            // 使当前的context出堆栈
            UIGraphicsEndImageContext();
        }
        // 如果图片大小大于200kb 在进行质量上压缩
        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循环压缩
                //scaledImageData > 1024 * thresholdSize_KB
                scaledImageData = UIImageJPEGRepresentation(newImage, 0.9);
            }
        }
        
        return scaledImageData
    }
}

三. text、view、color To Image

    /// 创建纯色图片
    ///
    /// - 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!
    }
    
    
    /// 文本转图片
    ///
    /// - 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转换成图片
    ///
    /// - Parameter view: 需要转换的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
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359

推荐阅读更多精彩内容