我正试图用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
}
}
最初图像如下:
一旦我旋转图像,它就会被裁剪成正方形。看起来是这样的:
这是不受欢迎的行为。我希望它的尺寸和以前一样。
最佳答案
@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/