美文网首页
swift 图片裁剪

swift 图片裁剪

作者: JACK_岩 | 来源:发表于2019-02-28 16:44 被阅读5次

    Swift:
    需求:图片等比例缩放,截取上部,不失真
    代码如下:

    extension UIImage {
        //将图片缩放成指定尺寸(多余部分自动删除)
        func scaled(to newSize: CGSize) -> UIImage {
            //计算比例
            let aspectWidth  = newSize.width/size.width
            let aspectHeight = newSize.height/size.height
            let aspectRatio = max(aspectWidth, aspectHeight)
            
            //图片绘制区域
            var scaledImageRect = CGRect.zero
            scaledImageRect.size.width  = size.width * aspectRatio
            scaledImageRect.size.height = size.height * aspectRatio
            scaledImageRect.origin.x    = 0
            scaledImageRect.origin.y    = 0
            
            //绘制并获取最终图片
            UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)//图片不失真
            draw(in: scaledImageRect)
            let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            return scaledImage!
        }
    }

    相关文章

      网友评论

          本文标题:swift 图片裁剪

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