我有一个非常简单的macOS应用程序(使用Xcode 8.2.1用Swift编写)。在我的主UI中,有一个带有自定义映像的NSButton (它表示扑克中的扑克牌)。当我点击那个按钮时,我希望它的图像被画成180度的旋转(倒转)。
我对仿射变换并不熟悉,但我认为这可能是可行的(它不起作用)。
@IBAction func buttonClicked(_ sender: NSButton) {
var transform = sender.layer?.affineTransform()
transform = transform?.rotated(by: 180.0 * (CGFloat.pi / 180))
sender.layer?.setAffineTransform(transform!)
}卡是正确旋转,但它是在一个新的位置画。
什么是正确的方式旋转一个按钮的形象180度,同时保持它的位置在它的父静态?
发布于 2017-02-08 10:58:53
为了旋转NSImage或NSButton图像,我使用Swift 3为NSImage编写了一个扩展。
您可以传递给函数:
这是一种叫它的方法:
@IBAction func button(_ sender: NSButton) {
sender.image = NSImage().imageRotatedByDegrees(rotationDegree: 180,
forImage: sender.image!)
}你的分机:
extension NSImage {
func imageRotatedByDegrees(rotationDegree degrees:CGFloat,forImage
image:NSImage) -> NSImage {
// calculate the bounds for the rotated image
var imageBounds = NSRect(origin: NSZeroPoint, size: image.size)
let boundsPath : NSBezierPath = NSBezierPath(rect: imageBounds)
var transform : NSAffineTransform = NSAffineTransform()
transform.rotate(byDegrees: degrees)
boundsPath.transform(using: transform as AffineTransform)
let rotatedBounds : NSRect = NSRect(origin: NSZeroPoint, size:
boundsPath.bounds.size)
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)
// set up the rotation transform
transform = NSAffineTransform()
transform.translateX(by: +(NSWidth(rotatedBounds) / 2), yBy:
+(NSHeight(rotatedBounds) / 2))
transform.rotate(byDegrees: degrees)
transform.translateX(by: -(NSWidth(rotatedBounds) / 2), yBy:
-(NSHeight(rotatedBounds) / 2))
// draw the original image, rotated, into the new image
rotatedImage.lockFocus()
transform.concat()
image.draw(in: imageBounds, from: NSZeroRect, operation:
NSCompositeCopy, fraction: 1.0)
rotatedImage.unlockFocus()
return rotatedImage
}
}发布于 2017-02-07 14:56:22
您必须使用转换转换将中心转换为0,0,然后旋转,然后再转换回中心,这样中心就是您想要的位置。类似于:
transform = transform?
.translatedBy(x: -self.center.x, y: -self.center.y)
.rotated(by: 180.0 * (CGFloat.pi / 180))
.translatedBy(x: self.center.x, y: self.center.y)https://stackoverflow.com/questions/42092747
复制相似问题