swift - 在Swift中旋转NSImage

标签 swift macos cocoa

我正试图用Swift在Mac操作系统上将图像旋转90度。
我有以下代码:

@IBAction func rotateImage(_ sender: Any) {
    let rotatedImage = image.imageRotatedByDegrees(degrees: CGFloat(90))
    self.imageView?.image = rotatedImage
}

以及
public extension NSImage {
    public func imageRotatedByDegrees(degrees:CGFloat) -> NSImage {

        var imageBounds = NSZeroRect
        imageBounds.size = self.size
        let pathBounds = NSBezierPath(rect: imageBounds)
        var transform = NSAffineTransform()
        transform.rotate(byDegrees: degrees)
        pathBounds.transform(using: transform as AffineTransform)
        let rotatedBounds:NSRect = NSMakeRect(NSZeroPoint.x, NSZeroPoint.y , self.size.width, self.size.height )
        let rotatedImage = NSImage(size: rotatedBounds.size)

        //Center the image within the rotated bounds
        imageBounds.origin.x = NSMidX(rotatedBounds) - (NSWidth(imageBounds) / 2)
        imageBounds.origin.y  = NSMidY(rotatedBounds) - (NSHeight(imageBounds) / 2)

        // Start a new transform
        transform = NSAffineTransform()
        // Move coordinate system to the center (since we want to rotate around the center)
        transform.translateX(by: +(NSWidth(rotatedBounds) / 2 ), yBy: +(NSHeight(rotatedBounds) / 2))
        transform.rotate(byDegrees: degrees)
        // Move the coordinate system bak to normal
        transform.translateX(by: -(NSWidth(rotatedBounds) / 2 ), yBy: -(NSHeight(rotatedBounds) / 2))
        // Draw the original image, rotated, into the new image
        rotatedImage.lockFocus()
        transform.concat()
        self.draw(in: imageBounds, from: NSZeroRect, operation: NSCompositingOperation.copy, fraction: 1.0)
        rotatedImage.unlockFocus()

        return rotatedImage
    }
}

最初图像如下:
enter image description here
一旦我旋转图像,它就会被裁剪成正方形。看起来是这样的:
enter image description here
这是不受欢迎的行为。我希望它的尺寸和以前一样。

最佳答案

enter image description here
在这里,我为您创建了一个简单的示例:)

@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
@IBAction func rotateBtn(_ sender: Any) {
    UIView.animate(withDuration: 2.0, animations: {
        self.imageView.transform = self.imageView.transform.rotated(by: CGFloat(M_PI_2))
    })
}

关于swift - 在Swift中旋转NSImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996615/

相关文章:

ios - 为什么按钮开关不起作用?

swift - 键盘文本字段是否取决于文本字段约束?

macos - 如何使用命令重启 Docker-for-mac?

iphone - 为什么我的变量没有被分配

objective-c - 多次用新数据刷新 NSTableView

ios - Swift - fatal error : Array index out of range

快速运行总和

c - mach_vm_region 与 mach_vm_region_recurse

bash - 如何在不创建临时文件的情况下像查看手册页一样查看 Markdown 文件?

ios - 正确管理addObserverForName :object:queue:usingBlock: