1

我正在尝试在 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 文档在内的几个不同地方学习的。现在,很明显我犯了一些天真的错误,但从逻辑上讲,我的代码对我来说似乎是正确的。如果有人能指出我的错误并让我了解它为什么不起作用,那就太好了。

4

1 回答 1

2

对于任何未来的访问者,该代码可以完美运行,如果需要,您可以使用它,除非确保在 nsview 中添加层之前,我们必须设置 nsview 想要层。

所以,变化将是......


- (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];
    
    /*HERE SETWANTSLAYER TO TRUE IN ORDER TO FIX*/
    [nsview setWantsLayer:YES];

    [nsview.layer addSublayer:syncFirst];
}

在使用此代码之前

请参阅评论中的讨论。有一些有用的提示,我在解决问题时忽略了这些提示。归功于-彼得霍西

于 2012-05-31T15:15:38.367 回答