我正在尝试在 NSView 中旋转 NSImage。首先,我将向您展示我到目前为止所做的事情。
图片 :
头文件
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@interface AppController : NSObject {
CALayer *syncFirst;
}
@property (weak) IBOutlet NSView *nsview;
- (IBAction)buttonClicked:(id)sender;
- (CGImageRef) convertToCGImageFromNasImage:(NSImage *) image;
@end
实现文件,只有相关方法
- (void)awakeFromNib {
NSImage *image = [NSImage imageNamed:@"SyncRing.png"];
//init layer
syncFirst = [CALayer layer];
//animatated content size init
syncFirst.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
syncFirst.position = CGPointMake(10, 10);
syncFirst.contents = (id)[self convertToCGImageFromNasImage:image];
[nsview.layer addSublayer:syncFirst];
}
/*To convert NSImage in CGImage*/
- (CGImageRef) convertToCGImageFromNasImage:(NSImage *) image {
NSData* cocoaData = [NSBitmapImageRep TIFFRepresentationOfImageRepsInArray: [image representations]];
CFDataRef carbonData = (__bridge CFDataRef)cocoaData;
CGImageSourceRef imageSourceRef = CGImageSourceCreateWithData(carbonData, NULL);
CGImageRef myCGImage = CGImageSourceCreateImageAtIndex(imageSourceRef, 0, NULL);
return myCGImage;
}
/*When button click animate the image*/
- (IBAction) buttonClicked:(id)sender {
CABasicAnimation* rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotationAnimation.toValue = [NSNumber numberWithFloat:(2 * M_PI) * 1];
rotationAnimation.duration = 1.0f;
rotationAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[syncFirst addAnimation:rotationAnimation forKey:@"rotateAnimation"];
}
问题 :
基本上我试图在单击按钮后旋转此图像。我正在尝试的代码不是 100% 实现,而是从包括 Apple 文档在内的几个不同地方学习的。现在,很明显我犯了一些天真的错误,但从逻辑上讲,我的代码对我来说似乎是正确的。如果有人能指出我的错误并让我了解它为什么不起作用,那就太好了。