- iOS: Drawing a CGImage into a subclass of CALayer during custom property animation in correct resolution
- #import "ScrollBarView.h"
- #import "ScrollBarLayer.h"
- @implementation ScrollBarView
- @synthesize sbl;
- - (id)initWithFrame:(CGRect)frame
- {
- self = [super initWithFrame:frame];
- if (self) {
- // Initialization code
- }
- return self;
- }
- - (void)setImagesWithName:(NSString*)imageName {
- ScrollBarLayer *ssbl = [[ScrollBarLayer alloc] init];
- ssbl.frame = CGRectMake(0, 0, 30, 30);
- [ssbl setImagesWithName:imageName];
- [self.layer addSublayer:ssbl];
- self.sbl = ssbl;
- [ssbl release];
- }
- - (void) dealloc {
- self.sbl = nil;
- [super dealloc];
- }
- - (void)setPercentageWithFloat:(CGFloat)perc {
- if(perc > 1.0){
- perc = 1.0;
- } else if(perc < 0) {
- perc = 0;
- }
- [self.sbl setPercentage:perc];
- CABasicAnimation* ba = [CABasicAnimation animationWithKeyPath:@"percentage"];
- ba.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
- ba.duration = 0.8;
- ba.toValue = [NSNumber numberWithFloat:perc];
- [self.sbl addAnimation:ba forKey:nil];
- }
- @end
- #import "ScrollBarLayer.h"
- @implementation ScrollBarLayer
- @synthesize filename;
- @dynamic percentage;
- - (id)init {
- self = [super init];
- if (self) {
- }
- return self;
- }
- - (void)setImagesWithName:(NSString*)imageName {
- self.frame = CGRectMake(0, 0, 30, 30);
- self.percentage = 0;
- self.filename = imageName;
- }
- + (BOOL) needsDisplayForKey:(NSString*)key {
- if([key isEqualToString:@"percentage"]) {
- return YES;
- }
- return [super needsDisplayForKey:key];
- }
- - (void) drawInContext:(CGContextRef)ctx {
- int imageIdx = (int)roundf((float)199 * self.percentage);
- NSString *thisfilename = [self.filename stringByAppendingString:[NSString stringWithFormat:@"%03d.png", i+1]];
- UIImage* c = [UIImage imageNamed:thisfilename];
- CGImageRef img = [c CGImage];
- CGSize sz = CGSizeMake(CGImageGetWidth(img), CGImageGetHeight(img));
- UIGraphicsBeginImageContextWithOptions(CGSizeMake(sz.width, sz.height), NO, 0.0);
- CGContextDrawImage(ctx, CGRectMake(0, 0, sz.width, sz.height), img);
- UIGraphicsEndImageContext();
- }
- - (void) dealloc {
- self.pictures = nil;
- self.filename = nil;
- [super dealloc];
- }
- @end
- #define IS_RETINA_DISPLAY() ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] == YES && [[UIScreen mainScreen] scale] == 2.00)
- ...
- UIGraphicsBeginImageContextWithOptions(CGSizeMake(sz.width, sz.height), NO, 0.0);
- if (IS_RETINA_DISPLAY())
- {
- CGContextDrawImage(ctx, CGRectMake(0, 0, sz.width/2.0f, sz.height/2.0f), img);
- } else
- {
- CGContextDrawImage(ctx, CGRectMake(0, 0, sz.width, sz.height), img);
- }
- UIGraphicsEndImageContext();
- ...