美文网首页
ios中关于image的一个缩放分类

ios中关于image的一个缩放分类

作者: Link913 | 来源:发表于2016-10-10 09:40 被阅读109次

手机中经常会遇到一些非常大的图片,当把它们导入到我们的缓存时有时会造成程序的闪退,即超过了125mb,此时我们有三种方法对图片进行压缩,前两者方法http://blog.csdn.NET/mideveloper/article/details/11473627这位哥们讲的已经很详细了,我自己用OC和Swift写了一个UIImage的分类,也比较好用.

OC:

+(UIImage *)reduceScaleToWidth:(CGFloat)width andImage:(UIImage *)image{
        
        if (image.size.width <= width) {
            return image;
        }
        
        CGFloat height = image.size.height * (width/image.size.width);
        
        CGRect rect = CGRectMake(0, 0, width, height);
        
        UIGraphicsBeginImageContext(rect.size);
        
        [image drawInRect:rect];
        
        UIImage * returnImage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        return returnImage;
    }

SWIFT

    /// 将图片按指定宽度缩放
    ///
    /// - parameter width: 指定宽度
    ///
    /// - returns: <#return value description#>
    func scaleToWidth(width: CGFloat) -> UIImage {
        if size.width <= width {
            return self
        }
        
        // 计算高度
        let height = size.height * (width / size.width)
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
        // 开启图形上下文
        UIGraphicsBeginImageContext(rect.size)
        
        // 画
        self.drawInRect(rect)
        
        // 取
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }

相关文章

网友评论

      本文标题: ios中关于image的一个缩放分类

      本文链接:https://www.haomeiwen.com/subject/cvbmyttx.html