-->

在NSImage中的NSView转动不灵(NSImage rotation in NSView is

2019-07-29 16:40发布

我试图转动里面的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%,但实现从几个不同的地方,包括苹果文档的教训。 现在,很明显,我做了一些幼稚的错误,但在逻辑上我的代码似乎是正确的我。 这将是巨大的,如果有人能指出我的错误,给我理解为什么它不工作。

Answer 1:

对于任何未来的访客,代码工作完美,如果你想除了确保你里面添加的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];
}

使用此代码之前

请参考意见的讨论。 有一些有用的提示,同时解决了我的问题,我已经忽视。 幸得- 彼得Hosey



文章来源: NSImage rotation in NSView is not working