我有一个名为UIImageView
的{{1}}:
bigBottle
bigBottle.image = [UIImage imageNamed:@"fullBootle.png"];
是一个装满100%的瓶子。
我需要两个步骤:
动画fullBootle.png
使填充效果从瓶子下方爬到50%填充。
我的代码如下:
bigBottle
另一种方法是让这个灌装瓶子的动画更简单,更节省内存?我有几十瓶随机填充百分比(让我们说瓶子80填满了20%)并且没有模糊的结果图像?
答案 0 :(得分:6)
以下是我对您的问题的简单实现。创建一个新的CALayer子类并实现一个名为percent的动态属性,然后将其设置为动画,
<强> ImageLayer.h 强>
#import <QuartzCore/QuartzCore.h>
@interface ImageLayer : CALayer
@property (nonatomic,assign )float percent;
@property (nonatomic, strong) NSString *imageName;
@end
<强> ImageLayer.m 强>
#import "ImageLayer.h"
@implementation ImageLayer
@dynamic percent;
+ (BOOL)needsDisplayForKey:(NSString *)key{
if([key isEqualToString:@"percent"]){
return YES;
}else
return [super needsDisplayForKey:key];
}
- (void)drawInContext:(CGContextRef)ctx{
UIGraphicsPushContext(ctx);
UIImage *image = [UIImage imageNamed:@"Bottle.jpg"];
[image drawInRect:self.bounds];
float heightToBeCovered = self.percent * CGRectGetHeight(self.bounds);
float verticalYPosition = CGRectGetHeight(self.bounds) - heightToBeCovered;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, verticalYPosition, CGRectGetWidth(self.bounds), heightToBeCovered )];
[[UIColor blackColor] setFill];
[path fill];
UIGraphicsPopContext();
}
@end
<强> ViewController.m 强>
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
ImageLayer *imageLayer = [ImageLayer layer];
imageLayer.position = self.view.center;
imageLayer.frame = self.view.bounds;
[self.view.layer addSublayer:imageLayer];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"percent"];
[animation setFromValue:@1];
[animation setToValue:@0];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
[animation setDuration:10.0];
[imageLayer addAnimation:animation forKey:@"imageAnimation"];
}
@end
答案 1 :(得分:0)
不,我只是用简单的动画制作这个补充:
self.bigBottle.frame =CGRectMake(self.bigBottle.frame.origin.x,self.bigBottle.frame.origin.y + self.bigBottle.frame.size.height,18,0); /*so the height is 0 on start*/
[self.bigBottle setClipsToBounds:YES]; //so image will be bounds to UIImageView bounds
[UIView animateWithDuration:2.0f animations:^{ self.bigBottle.frame =CGRectMake(self.bigBottle.frame.origin.x,self.bigBottle.frame.origin.y -43 ,18,self.bigBottle.frame.size.height+43); //where 43 is a value I generate random