美文网首页Swift
swift-通过图形上下文实现图片缩放

swift-通过图形上下文实现图片缩放

作者: Coder东 | 来源:发表于2017-03-30 16:01 被阅读7次
//
//  ViewController.swift
//  Swift-通过图形上下文实现图片缩放
//
//  Created by 品德信息 on 2016/12/29.
//  Copyright © 2016年 品德信息. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    let image = UIImage(named:"startup")
    
    let scaledImage = scaleImage12(image: image!, newSize: CGSize(width:180,height:180))
    
    let imageView = UIImageView(image:scaledImage)
    imageView.center = CGPoint(x:160,y:160)
    self.view.addSubview(imageView)
    
    
    
    
}
//创建一个方法,传递一个图像参数和一个缩放的参数,实现将图像缩放至指定比例的功能
func scaleImage12(image:UIImage,newSize:CGSize) -> UIImage{
    
    let imageSize = image.size
    let width = imageSize.width
    //获取源图像的高
    let height = imageSize.height
    //计算图像新尺寸与旧尺寸的款高比
    let widthFactor = newSize.width/width
    let heightFactor = newSize.height/height
    //获取最小的比例值
    let scaleFactor = (widthFactor<heightFactor) ? widthFactor :heightFactor
    //计算图像新的宽高,并将新宽高构建成标准的CGSize对象
    let scaleWith = width * scaleFactor
    let scaleHeight = height * scaleFactor
    let  targetSize = CGSize(width:scaleWith,height:scaleHeight)

    UIGraphicsBeginImageContext(targetSize)
    image.draw(in: CGRect(x:0,y:0,width:scaleWith,height:scaleHeight))
    //获取上下文内容,将内容写到新的图像对象中
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    return newImage!
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

相关文章

网友评论

    本文标题:swift-通过图形上下文实现图片缩放

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