I'm working on a species ID app and would like to populate a layer with sprites based on which animal you select on the main layer. I've made each animal a menu item, and can get my info layer to appear when pressing the button, but how can I set it up so the layer shows the right data depending on which animal you select? The info layer is not a full screen layer, but rather an overlaying layer that only fills about 75% of the screen, which is why I'm going with a layer rather than a scene. I know I can create a new layer for each animal (approx 50) and code it so each button calls its own layer, but I think populating based on which button is pressed would make for cleaner code. If flamingoButton is pressed, sprite is filled with flamingo.png and label is populated with flamingo information. How do I get my info layer to listen to the buttons on the main layer?
MainLayer.m code:
-(id) init
{
if( (self=[super init]))
{
CCMenuItemImage *flamingoButton = [CCMenuItemImage itemFromNormalImage:#"Explore-sign.png" selectedImage:#"Explore-sign.png" target:self selector:#selector(showSecondLayer:)];
flamingoButton.position = CGPointMake(0, 60);
flamingoButton.tag = 101;
CCMenu *menu = [CCMenu menuWithItems:flamingoButton, nil];
[self addChild:menu];
}
return self;
}
-(void) showSecondLayer: (id) sender
{
CCMenuItemImage *item = (CCMenuItemImage *) sender;
int itemID = item.tag;
secondLayer = [SecondLayer node];
secondLayer.position = CGPointMake(0, 700);
[self addChild:secondLayer];
CCMoveTo *moveLayer = [CCMoveTo actionWithDuration:1.0 position:CGPointMake(0, 0)];
[secondLayer runAction:moveLayer];
}
SecondLayer.m (the info layer)
-(id) init
{
if( (self=[super init]))
{
//Change this sprite image based on button from main layer. I don't have it coded in yet, but I understand the concept of putting a variable in the file string using %# or %d
CCSprite *infoCard = [CCSprite spriteWithFile:#"species1.png"];
infoCard.anchorPoint = CGPointMake(0.5, 0);
infoCard.position = CGPointMake(512, 0);
[self addChild:infoCard];
}
return self;
}
Ok, this might work:
//MainLayer:
-(id) init
{
if( (self=[super init]))
{
CCMenuItem *flamingoButton = [CCMenuItemImage itemFromNormalImage:#"Explore-sign.png"
selectedImage:#"Explore-sign.png"
target:self
selector:#selector(showSecondLayer:)];
flamingoButton.position = ccp(0, 60);
flamingoButton.tag = 1;
CCMenu *menu = [CCMenu menuWithItems:flamingoButton, nil];
[self addChild:menu];
}
return self;
}
-(void) showSecondLayer: (CCMenuItem*) sender
{
secondLayer = [SecondLayer layerWithTag:[sender tag]];
secondLayer.position = ccp(0, 700);
[self addChild:secondLayer];
CCMoveTo *moveLayer = [CCMoveTo actionWithDuration:1.0 position:ccp(0, 0)];
[secondLayer runAction:moveLayer];
}
//Second Layer.h
+(id)layerWithTag:(NSInteger)aTag;
-(id) initWithTag:(NSInteger)aTag;
//Second Layer.m:
+(id)layerWithTag:(NSInteger)aTag {
return [[[SecondLayer alloc] initWithTag:aTag] autorelease];
}
-(id) initWithTag:(NSInteger)aTag
{
if( (self=[super init]))
{
//Change this sprite image based on button from main layer. I don't have it coded in yet, but I understand the concept of putting a variable in the file string using %# or %d
CCSprite *infoCard = [CCSprite spriteWithFile:[NSString stringWithFormat:#"species%d.png", aTag]];
infoCard.anchorPoint = ccp(0.5, 0);
infoCard.position = ccp(512, 0);
[self addChild:infoCard];
}
return self;
}
EDIT:
Even though the previous solution works, it's not intuitive, and I feel I am breaking some OOP concepts. Most importantly, it is only useable given that your info about the animal can be retrieved using a single int! .. Using it this way is a BIT better, it's totally up to you to decide:
Ehm, so, I would suggest you set up an Entity Class first:
//AnimalResources.h
#import "Blahblahblah"
//Give it a good name, I was always bad at Science:
#interface AnimalResources {
//load all your properties:
NSString* info;
CCSprite* sprite;
...
}
//set the properties as needed:
//Make sure you properly manage this!! It is retained!
#property (nonatomic, retain) CCSprite* sprite;
...
//method prototype (signature.. am not sure)
//Now, we shall build on the fact that it will be easy for you to map an integer to the right resources:
+(id)animalResourcesWithTag:(NSInteger)aTag;
-(id)initAnimalResourcesWithTag:(NSInteger)aTag;
//AnimalResources.m:'
#synthesize sprite, ... ;
+(id)animalResourcesWithTag:(NSInteger)aTag {
[[[AnimalResources alloc] initAnimalResourcesWithTag:aTag] autorelease];
}
-(id)initAnimalResourcesWithTag:(NSInteger)aTag {
if ((self = [super init])) {
//use tag to retrieve the resources:
//might use the stringFormat + %d approach, or have a dictionary/array plist, that maps an int to a dictionary of resource keys.
//string way of doing things:
self.sprite = [CCSprite spriteWithFile:[NSString stringWithFormat:#"species%d.png", aTag]];
...
//Dictionary: dict/array is an NSDictionary/NSArray read from disk sometime. Don't read it here, since it
//will read the file from disk many times if you do --> BAD. I could explain a rough way to do that if you
//need help
animalDict = [dict objectForKey:[NSString stringWithFormat:#"species%d.png", aTag]];
//OR...
animalDict = [array objectAtIndex:aTag];
//better to have #"spriteNameKey" defined in a macro somewhere: #define kAnimalResourceKeySprite #"SpriteKey"
self.sprite = [CCSprite spriteWithFile:[animalDict objectForKey:#"SpriteNameKey"]];
....
}
return self;
}
Phew! Then .. you guessed it!
-(void) showSecondLayer: (CCMenuItem*) sender
{
secondLayer = [SecondLayer layerWithAnimalResources:[AnimalResources animalResourcesWithTag:[sender tag]]];
secondLayer.position = ccp(0, 700);
[self addChild:secondLayer];
CCMoveTo *moveLayer = [CCMoveTo actionWithDuration:1.0 position:ccp(0, 0)];
[secondLayer runAction:moveLayer];
}
//Second Layer.h
+(id)layerWithAnimalResources:(AnimalResources*)resource;
-(id)initWithAnimalResources:(AnimalResources*)resource;
//Second Layer.m:
+(id)layerWithAnimalResources:(AnimalResources*)resource {
return [[[SecondLayer alloc] initWithAnimalResources:aTag] autorelease];
}
-(id) initWithAnimalResources:(AnimalResources*)resource
{
if( (self=[super init]))
{
//Change this sprite image based on button from main layer. I don't have it coded in yet, but I understand the concept of putting a variable in the file string using %# or %d
CCSprite *infoCard = [resource sprite];
infoCard.anchorPoint = ccp(0.5, 0);
infoCard.position = ccp(512, 0);
[self addChild:infoCard];
}
return self;
}
Give each menu item a unique id. In the method which you invoke on the tap of the button, you can reference the id of the sender. Use this id to populate the new layer with the unique information.
- (void) buttonPressed: (id) sender
{
MenuItem* item = (MenuItem*) sender;
int itemID = item.tag;
// Get unique data based on itemID and add new layer
}
EDIT: Per your code updates
-(void) showSecondLayer: (id) sender
{
CCMenuItemImage *item = (CCMenuItemImage *) sender;
int itemID = item.tag;
secondLayer = [SecondLayer node];
[secondLayer setItem: itemID]; // ADDED
secondLayer.position = CGPointMake(0, 700);
[self addChild:secondLayer];
CCMoveTo *moveLayer = [CCMoveTo actionWithDuration:1.0 position:CGPointMake(0, 0)];
[secondLayer runAction:moveLayer];
}
SecondLayer.m (the info layer)
-(id) init
{
if( (self=[super init]))
{
// Removed
}
return self;
}
-(void) setItem: (int) item
{
CCSprite *infoCard = [CCSprite spriteWithFile:[NSString stringWithFormat:#"species%d", item]];
infoCard.anchorPoint = CGPointMake(0.5, 0);
infoCard.position = CGPointMake(512, 0);
[self addChild:infoCard];
}
Related
I would like to call a method that rotates a sprite when a particular frame in displayed. I got a few ideas from this post but I am having issues as to how I should implement it. How would I define my dictionary for accessing 3rd frame and link it to the selector? Below is what I've done. Please note that it's work-in-progress.
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super's" return value
if( (self=[super init]) ) {
CCSpriteBatchNode* batchNode;
CCSpriteFrameCache* frameCache;
frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
[frameCache addSpriteFramesWithFile:#"cat-hd.plist"];
batchNode = [CCSpriteBatchNode batchNodeWithFile:#"cat-hd.pvr.ccz"];
[self addChild:batchNode];
CCSprite* wallbg = [CCSprite spriteWithSpriteFrameName:#"firstBg.png"];
wallbg.position= ccp(240.0, 160.0);
//wallbg.anchorPoint = ccp(0.5, 0.5);
[batchNode addChild:wallbg];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(rotateAnimationFrame:) name:CCAnimationFrameDisplayedNotification object:nil];
NSMutableArray* catAnimationArray = [[NSMutableArray alloc]init];
for(int i = 1; i < 7; i++) // i< number of frames in the plist File Name
{
CCLOG(#"item %d added", i);
[catAnimationArray addObject:
[frameCache spriteFrameByName:
[NSString stringWithFormat:#"blackCat%d.png", i]]]; }
CCSprite* catSprite = [CCSprite spriteWithSpriteFrameName: #"blackCat1.png"];
CGSize screenSize = [[CCDirector sharedDirector] winSize];
catSprite.position = ccp(screenSize.width/2, screenSize.height/2);
CCAnimation *animation = [CCAnimation animationWithSpriteFrames:catAnimationArray delay:0.3];
CCAnimationFrame* thirdFrame = [animation.frames objectAtIndex:2];
NSDictionary* uInfo = //how should I define my dictionary?
id action =[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation :animation]];
[catSprite runAction:action];
[batchNode addChild:catSprite];
}
return self;
}
// on "dealloc" you need to release all your retained objects
-(void)rotateAnimationFrame:(NSNotification*)notification {
NSDictionary *userInfoDictionary = [notification userInfo];
if ([[notification name] isEqualToString:#"CCAnimationFrameDisplayedNotification"]) {
CCSprite* thirdAnim = [CCSprite spriteWithSpriteFrame:#"blackCat3.png"];
CCRotateTo *rotateRight = [CCRotateBy actionWithDuration:0.2 angle:40.0];
[thirdAnim runAction:rotateRight];
}
I want trigger the keyDown Event with every Key action. Therefore I have created a subclass of NSView.
#interface CodrTextView : NSView {
NSTextField *lineNumberSpace;
NSTextView *mainTextView;
}
- (id) initWithTextView:(NSTextView *)textView lineNumberSpace:(NSTextField *)textField;
I already have the method's:
- (id) initWithTextView:(NSTextView *)textView lineNumberSpace:(NSTextField *)textField {
self = [self init];
if (self){
mainTextView = textView;
lineNumberSpace = textField;
}
return self;
}
- (BOOL) acceptsFirstResponder {
return YES;
}
- (BOOL)canBecomeKeyView {
return YES;
}
My plan is to count the lines in the textView and write the numbers in the lineNumberSpace. I know that the methods work, because I have test it already with an IBAction on a button. This is the method:
- (long) getLineCount{
NSString *content = [mainTextView string];
NSUInteger numberOfLines, index, contentLength = [content length];
for (index = 0, numberOfLines = 0; index < contentLength; numberOfLines++){
index = NSMaxRange([content lineRangeForRange:NSMakeRange(index, 0)]);
}
NSLayoutManager *layoutManager = [mainTextView layoutManager];
NSUInteger numberOfGlyphs =[layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
}
numberOfLines++;
return numberOfLines;
}
- (void)keyDown:(NSEvent *)event {
NSMutableString *lineNumberString = [NSMutableString string];
long numberOfLines = [self getLineCount];
for (int i = 1; i <= numberOfLines; i++){
[lineNumberString appendString:([NSString stringWithFormat:#"%d \n", i])];
}
[lineNumberSpace setStringValue:lineNumberString];
}
This method works surely. The problem is, with a button the number in the lineNumberSpace is changing correctly but with the keyDown Event it don't work. What is my mistake here?
Ahhh, looking at your code I now realize what the problem is.
Your "CodrTextView" object is not subclassed from "NSTextView" (and also, when you instantiate the object programatically or via your XIB or Storyboard, make sure the text view object is a custom class of "CodrTextView" and not just another "NSTextView"), so it's not actually getting the "acceptsFirstResponder" or "canBecomeKeyView" method calls either.
You need to descend "CodrTextView" from "NSTextView" instead of "NSView", OR you need to create another subclassed "NSTextView" object which will receive the "keyDown:" event and then it'll call the code that calculates the string that goes into "lineNumberSpace" of your main view.
Does this make sense to you now?
I have a problem with the PIn color mapView when a refresh is done.
In my I app i display some point with two color in order to identify if a service is available.
On the first start, no problems appear. The code is the follower:
- (void)viewDidLoad
{
[super viewDidLoad];
[self dowloadPoint]; // here I exucte the first start
}
- (void)dowloadPoint{
NSURL *url1 =[NSURL URLWithString:#"http:MYUSRL"];
NSData *datos1 =[[NSData alloc] initWithContentsOfURL:url1];
[self plotBarPosition:datos_string1]; //Here I call the plotBarPosition method
}
- (void)plotBarPosition:(NSString *)datos_string1 {
for (id<MKAnnotation> annotation in _mapView.annotations) {
[_mapView removeAnnotation:annotation];
}
// Parse the string into JSON
NSDictionary *json = [(NSDictionary*)[datos_string1 JSONValue]objectForKey:#"features"];
// Get the objects you want, e.g. output the second item's client id
NSArray *items_properties = [json valueForKeyPath:#"properties"];
NSArray *items_geo = [json valueForKeyPath:#"geometry"];
for (int i = 0; i < [json count]; i++){
NSString *nomprePunto =[[items_properties objectAtIndex:i] objectForKey:#"title"];
NSNumber *lat =[[[items_geo objectAtIndex:i] objectForKey:#"coordinates"] objectAtIndex:0];
NSNumber *lon =[[[items_geo objectAtIndex:i] objectForKey:#"coordinates"] objectAtIndex:1];
CLLocationCoordinate2D coordinate;
coordinate.latitude = lat.doubleValue;
coordinate.longitude = lon.doubleValue;
//ESTADO
NSString *description = [[items_properties objectAtIndex:i] objectForKey:#"description"];
NSString *estado_punto = [[NSString alloc]init];
if ([description rangeOfString:#"Averiado"].location == NSNotFound) {
estado_punto = #"Available";
} else {
estado_punto = #"NOt Available";
averiados ++;
}
NSString *averiadosStr = [NSString stringWithFormat:#"%d",averiados];
averiadosLabel.text = averiadosStr;
MyLocation *location =[[MyLocation alloc] initWithName:nomprePunto coordinate:coordinate estado:estado_punto];
[_mapView addAnnotation:location];
}
}
- (MKPinAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(MyLocation *)annotation {
static NSString *identifier = #"MyLocation";
if ([annotation isKindOfClass:[MyLocation class]]) {
MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
if([[annotation estado] isEqualToString:#"En Servicio"])
annotationView.pinColor = MKPinAnnotationColorGreen;
} else {
annotationView.annotation = annotation;
}
return annotationView;
}
return nil;
}
But whe I add a refres button that is function is simply a refreshcalling the dowloadPoint once again,
- (IBAction)refresh{
[self dowloadPoint];
}
the color of pins change in a "random manner", not corrisponding with the real state of point.
Any ideas about what is happening? Thanks in advance.
EDIT: It seemps pproblems is due to:
for (id<MKAnnotation> annotation in _mapView.annotations) {
[_mapView removeAnnotation:annotation];
}
erasing it, the app work properly but pins area drown abow the previous ones...:S
The default color of the pin is red. You set it to green if the estado property of your MyLocation object is equal to #"En Servicio". I understand that sometimes the color is red, when your estado property is equal to #"En Servicio", or sometimes green when it is not.
One reason could be that your MyLocation object simply does no longer exist when you press the refresh button. In this case, you might still have a pointer to the memory location where it once existed, but this location may have been overwritten by anything, causing a random color.
This can happen e.g. if your MyLocation object has been created as an autorelease object that has been released when you returned to the main event loop, i.e. to handle user interactions.
This should not be the case if you are using ARC.
I am new to Mac development, Do we have any methods like
imagev = [NSArray arrayWithObjects
I need some thing like what we do in iOS want to do in mac,
imageVie.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"1.png"],[UIImage imageNamed:#"2.png"],
[UIImage imageNamed:#"3.png"],[UIImage imageNamed:#"4.png"],
[UIImage imageNamed:#"5.png"],[UIImage imageNamed:#"6.png"],
[UIImage imageNamed:#"7.png"] ,nil];
In iPhone, How can i animate
Regards
I found someone using a Core Animation approach to this issue which was close enough for me. I modified it slightly. You need to #import QuartzCore;
- (void)awakeFromNib
{
CALayer *layer = [CALayer layer];
NSMutableArray *spinnerImages = [NSMutableArray arrayWithCapacity:30u];
for (NSUInteger i = 0; i < 30; ++i)
{
NSString *imageName = [NSString stringWithFormat:#"spinner%#", #(i)];
[spinnerImages addObject:[NSImage imageNamed:imageName]];
}
self.spinnerImages = spinnerImages;
layer.frame = self.imageView.bounds;
[self.imageView setLayer:layer]; // This view is just a container for the layer. Its frame can be managed by a xib.
self.imageView.wantsLayer = YES;
self.spinnerLayer = layer;
}
Then you can animate it like this:
- (void)stopAnimating
{
if ([self.layer.animationKeys containsObject:kAnimationKey])
{
[self.layer removeAnimationForKey:kAnimationKey];
}
}
- (void)startAnimating
{
if ([self.layer.animationKeys containsObject:kAnimationKey])
{
return;
}
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:kAnimationKey];
[animation setCalculationMode:kCAAnimationDiscrete];
[animation setDuration:1.0f];
[animation setRepeatCount:HUGE_VALF];
[animation setValues:self.spinnerImages];
[self.spinnerLayer addAnimation:animation forKey:kAnimationKey];
}
Building on the great answer by Ben Flynn.
In Swift 3:
// This needs to happen around init.
// NSView (and who inherit from it) does not come with a layer.
// self.layer will be nil at init.
self.layer = CALayer()
self.wantsLayer = true
let layer = CALayer()
let keyPath = "contents" // (I did not find a constant for that key.)
let frameAnimation = CAKeyframeAnimation(keyPath: keyPath)
frameAnimation.calculationMode = kCAAnimationDiscrete
// Duration
// This is the duration of one cycle
let durationOfAnimation: CFTimeInterval = 2.5
frameAnimation.duration = durationOfAnimation
frameAnimation.repeatCount = HUGE// can also use Float.infinity
let imageSeq: [NSImage] = imageSequance // Your images to animate
frameAnimation.values = imageSeq
// Sadly, there are no layout constraints on CALayer.
// If your view will be resized while animating, you'll need to override
// 'func layout()' and calculate aspect ratio if needs be
let layerRect = CGRect(origin: CGPoint.zero, size: self.frame.size)
layer.frame = layerRect
layer.bounds = layerRect
layer.add(frameAnimation, forKey: keyPath)
self.layer?.addSublayer(layer)
If the view is expected to be resized:
Remove these lines:
let layerRect = CGRect(origin: CGPoint.zero, size: self.frame.size)
layer.frame = layerRect
layer.bounds = layerRect
And call self.needsLayout = true after adding the sublayer. This will cause the layout() to be called.
//let layerRect = CGRect(origin: CGPoint.zero, size: self.frame.size)
//layer.frame = layerRect
//layer.bounds = layerRect
layer.add(frameAnimation, forKey: keyPath)
self.layer?.addSublayer(layer)
self.needsLayout = true
Lastly, override layout():
override func layout() {
super.layout()
var layerFrame = CGRect(origin: CGPoint.zero, size: self.frame.size)
self.myLayer.frame = layerFrame
self.myLayer.bounds = // Adjust ratio as needed.
}
Cocoa doesn't have anything like animatedImageWithImages:duration:. Images in Cocoa can vary in space (different resolutions) and color depth, but not time; a single image is always a static image, never animated.
(There might be an exception for animated GIFs, but GIFs can't display more than 255 or 256 colors per frame, and do not support partial transparency. Moreover, I haven't tried creating or displaying GIFs using the NSImage or CGImage machinery.)
What you'll need to do is create not an image, but a movie. Add images to the movie, varying each one's duration to achieve the playback speed you want. Then, display your movie in a movie view, optionally with the controller hidden.
Swift 4.2
I couldn’t get the previous answers get to work until I added a beginTime. Since Swift 3 some constants changed too. So I’ve converted the solution to Swift 4.2. Also, I thought it would be handy to create it as a CALayer extention:
extension CALayer {
static func image(sequence: [NSImage], duration: CFTimeInterval? = nil, frame: CGRect? = nil) -> CALayer {
let layer = CALayer()
if let f = frame { layer.frame = f }
layer.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
let keyPath = "contents"
let keyFrameAnimation = CAKeyframeAnimation(keyPath: keyPath)
keyFrameAnimation.values = sequence
keyFrameAnimation.calculationMode = .discrete
keyFrameAnimation.fillMode = .forwards
keyFrameAnimation.duration = duration ?? CFTimeInterval(sequence.count / 18)
keyFrameAnimation.repeatCount = Float.infinity
keyFrameAnimation.autoreverses = false
keyFrameAnimation.isRemovedOnCompletion = false
keyFrameAnimation.beginTime = 0.0
layer.add(keyFrameAnimation, forKey: keyPath)
return layer
}
}
Use it like
let sequenceLayer = CALayer.image(sequence: imageSequence, duration: 0.55, frame: yourView.bounds)
#interface AnimatedNSImage : NSImage
#property (nonatomic, retain) IBInspectable NSImageView *delegate;
#property (nonatomic, readonly) NSArray *frames;
#property (nonatomic, readonly) CGFloat duration;
- (instancetype) initWithImages:(NSArray*)frames duration:(CGFloat)duration;
#end
And in the .m file...
#interface AnimatedNSImage () {
NSTimer *_scheduledTimer;
NSArray *_frames;
NSUInteger _frameIndex;
CGFloat _duration;
}
#end
#implementation AnimatedNSImage
#synthesize delegate;
- (NSArray *) frames
{
return _frames;
}
- (CGImageRef) CGImage
{
if (_frames && _frames.count >0) {
NSImage *_frame = _frames[_frameIndex];
return _frame.CGImage;
}
return nil;
}
- (NSArray<NSImageRep *> *) representations
{
NSImage *_frame = _frames[_frameIndex];
return _frame.representations;
}
- (CGFloat) duration
{
return _duration;
}
- (void) __showNextFrame:(id)sender
{
_frameIndex = (_frameIndex + 1) % _frames.count;
if (delegate) {
[delegate setNeedsDisplay:YES];
}
}
- (NSSize) size
{
if (_frames && _frames.count >0) {
NSImage *_frame = _frames[_frameIndex];
return _frame.size;
}
return CGSizeZero;
}
- (void) setup
{
_scheduledTimer = [NSTimer scheduledTimerWithTimeInterval:_duration target:self selector:#selector(__showNextFrame:) userInfo:nil repeats:YES];
}
- (void) dealloc
{
[_scheduledTimer invalidate];
_scheduledTimer = nil;
}
- (instancetype) initWithImages:(NSArray *)frames duration:(CGFloat)duration
{
self = [super init];
if (self) {
_frames = frames;
_duration = duration / 100.0f;
[self setup];
}
return self;
}
#end
Note that you will have to assign the delegate (to the NSImageView) in order to invoke a refresh..
An example....
IBOutlet NSImageView *_testGifView;
AnimatedNSImage *_animatedImage = [NSImage animatedImageWithAnimatedGIFURL:[NSURL URLWithString:#"https://media.giphy.com/media/B2zB8mHrHHUXS57Cuz/giphy.gif"]];
_testGifView.image = _animatedImage;
_animatedImage.delegate = _testGifView;
The scheduled timer of course can be adjusted as required as the input time is in centiseconds (as opposed to minutes).
I have a custom view in an NSStatusItem object.
This view displays icons. It's also able to show a progress, but you have to call [self.statusitemview setProgressValue:theValue];
I have a set of icons, and it chooses the right one using this value.
This seems very jerky, because the executed process doesn't send updates all the time.
So I would like to animate this.
I would like to call the animation like you can with other cocoa-controls:
[[self.statusItemView animator] setProgressValue:value];
If that's at all possible
What is the proper way to do this?
I wouldn't want to use an NSTimer.
EDIT
The images are drawn using the drawRect: method
Here's the code:
- (void)drawRect:(NSRect)dirtyRect
{
if (self.isHighlighted) {
[self.statusItem drawStatusBarBackgroundInRect:self.bounds withHighlight:YES];
}
[self drawIcon];
}
- (void)drawIcon {
if (!self.showsProgress) {
[self drawIconWithName:#"statusItem"];
} else {
[self drawProgressIcon];
}
}
- (void)drawProgressIcon {
NSString *pushed = (self.isHighlighted)?#"-pushed":#"";
int iconValue = ((self.progressValue / (float)kStatusItemViewMaxValue) * kStatusItemViewProgressStates);
[self drawIconWithName:[NSString stringWithFormat:#"statusItem%#-%d", pushed, iconValue]];
}
- (void)drawIconWithName:(NSString *)iconName {
if (self.isHighlighted && !self.showsProgress) iconName = [iconName stringByAppendingString:#"-pushed"];
NSImage *icon = [NSImage imageNamed:iconName];
NSRect drawingRect = NSCenterRect(self.bounds, icon);
[icon drawInRect:drawingRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0 respectFlipped:YES hints:nil];
}
- (void)setProgressValue:(int)progressValue {
if (progressValue > kStatusItemViewMaxValue || progressValue < 0) {
#throw [NSException exceptionWithName:#"Invalid Progress Value"
reason:[NSString stringWithFormat:#"The value %d id invalid. Range {0 - %d}", progressValue, kStatusItemViewMaxValue]
userInfo:nil];
}
_progressValue = progressValue;
[self setNeedsDisplay:YES];
}
- (void)setShowsProgress:(BOOL)showsProgress {
if (!showsProgress) self.progressValue = 0;
_showsProgress = showsProgress;
[self setNeedsDisplay:YES];
}
It has to be possible somehow.
Since standard controls from Apple are drawn using the drawRect:, but have smooth animations...
To animate custom properties, you need to make your view conform to the NSAnimatablePropertyContainer protocol.
You can then set up multiple custom properties as animatable (in addition to the properties already supported by NSView), and then you can simply use your views' animator proxy to animate the properties:
yourObject.animator.propertyName = finalPropertyValue;
Apart from making animation very simple, it also allows you to animate multiple objects simultaneously using an NSAnimationContext:
[NSAnimationContext beginGrouping];
firstObject.animator.propertyName = finalPropertyValue1;
secondObject.animator.propertyName = finalPropertyValue2;
[NSAnimationContext endGrouping];
You can also set the duration and supply a completion handler block:
[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0.5];
[[NSAnimationContext currentContext] setCompletionHandler:^{
NSLog(#"animation finished");
}];
firstObject.animator.propertyName = finalPropertyValue1;
secondObject.animator.propertyName = finalPropertyValue2;
[NSAnimationContext endGrouping];
For a standard NSView object, if you want to add animation support to a property in your view, you just need to override the +defaultAnimationForKey: method in your view and return an animation for the property:
//declare the default animations for any keys we want to animate
+ (id)defaultAnimationForKey:(NSString *)key
{
//in this case, we want to add animation for our x and y keys
if ([key isEqualToString:#"x"] || [key isEqualToString:#"y"]) {
return [CABasicAnimation animation];
} else {
// Defer to super's implementation for any keys we don't specifically handle.
return [super defaultAnimationForKey:key];
}
}
I've created a simple sample project that shows how to animate multiple properties of a view simultaneously using the NSAnimatablePropertyContainer protocol.
All your view needs to do to update successfully is make sure that setNeedsDisplay:YES is called when any of the animatable properties are modified. You can then get the values of those properties in your drawRect: method and update the animation based on those values.
I have answered similar question here
You can't animate custom properties with animator, but you can write custom animation if you need, though it's not best idea.
Updated (Custom Animation):
- (void) scrollTick:(NSDictionary*) params
{
static NSTimeInterval timeStart = 0;
if(!timeStart)
timeStart = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval stTime = timeStart;
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval totalTime = [[params valueForKey:#"duration"] doubleValue];
if(currentTime > timeStart + totalTime)
{
currentTime = timeStart + totalTime;
timeStart = 0;
}
double progress = (currentTime - stTime)/totalTime;
progress = (sin(progress*3.14-3.14/2.0)+1.0)/2.0;
NSClipView* clip = [params valueForKey:#"target"];
float startValue = [[params valueForKey:#"from"] floatValue];
float endValue = [[params valueForKey:#"to"] floatValue];
float newValue = startValue + (endValue - startValue)*progress;
[self setProperty:newValue];
if(timeStart)
[self performSelectorOnMainThread:#selector(scrollTick:) withObject:params waitUntilDone:NO];
}
- (void) setAnimatedProperty:(float)newValue
{
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:self.property], #"from",
[NSNumber numberWithFloat:newValue],#"to",
[NSNumber numberWithFloat:1.0],#"duration",
nil];
[self performSelectorOnMainThread:#selector(scrollTick:) withObject:params waitUntilDone:NO];
}