Last active
January 24, 2024 15:58
-
-
Save eiskalteschatten/dac3190fce5d38fdd3c944b45a4ca469 to your computer and use it in GitHub Desktop.
A function written in Swift to resize an NSImage proportionately
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ImageResizer.swift | |
// | |
// Created by Alex Seifert on 18/06/2016. | |
// http://www.alexseifert.com | |
// | |
import Foundation | |
import Cocoa | |
// Function for resizing an NSImage | |
// Parameters: | |
// image:NSImage -> The NSImage that will be resized | |
// maxSize:NSSize -> An NSSize object that will define the new size of the image | |
func resizeImage(image:NSImage, maxSize:NSSize) -> NSImage { | |
var ratio:Float = 0.0 | |
let imageWidth = Float(image.size.width) | |
let imageHeight = Float(image.size.height) | |
let maxWidth = Float(maxSize.width) | |
let maxHeight = Float(maxSize.height) | |
// Get ratio (landscape or portrait) | |
if (imageWidth > imageHeight) { | |
// Landscape | |
ratio = maxWidth / imageWidth; | |
} | |
else { | |
// Portrait | |
ratio = maxHeight / imageHeight; | |
} | |
// Calculate new size based on the ratio | |
let newWidth = imageWidth * ratio | |
let newHeight = imageHeight * ratio | |
// Create a new NSSize object with the newly calculated size | |
let newSize:NSSize = NSSize(width: Int(newWidth), height: Int(newHeight)) | |
// Cast the NSImage to a CGImage | |
var imageRect:CGRect = CGRectMake(0, 0, image.size.width, image.size.height) | |
let imageRef = image.CGImageForProposedRect(&imageRect, context: nil, hints: nil) | |
// Create NSImage from the CGImage using the new size | |
let imageWithNewSize = NSImage(CGImage: imageRef!, size: newSize) | |
// Return the new image | |
return imageWithNewSize | |
} |
Yep... unfortunately this really does not resize anything...
Anybody has a good working solution for macOS?
Could you provide more details about the problems your having with it?
I've used this code verbatim in two different Swift-based projects without a problem...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
be careful, this does not resize anything !