How to easily resize/optimize an image size with iOS?

后端 未结 18 1505
温柔的废话
温柔的废话 2020-11-22 11:05

My application is downloading a set of image files from the network, and saving them to the local iPhone disk. Some of those images are pretty big in size (widths larger tha

18条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:38

    I just wanted to answer that question for Cocoa Swift programmers. This function returns NSImage with new size. You can use that function like this.

            let sizeChangedImage = changeImageSize(image, ratio: 2)
    
    
    
    
    
    
     // changes image size
    
        func changeImageSize (image: NSImage, ratio: CGFloat) -> NSImage   {
    
        // getting the current image size
        let w = image.size.width
        let h = image.size.height
    
        // calculating new size
        let w_new = w / ratio 
        let h_new = h / ratio 
    
        // creating size constant
        let newSize = CGSizeMake(w_new ,h_new)
    
        //creating rect
        let rect  = NSMakeRect(0, 0, w_new, h_new)
    
        // creating a image context with new size
        let newImage = NSImage.init(size:newSize)
    
    
    
        newImage.lockFocus()
    
            // drawing image with new size in context
            image.drawInRect(rect)
    
        newImage.unlockFocus()
    
    
        return newImage
    
    }
    

提交回复
热议问题