使用动画从完整的UIImage填充UIImageView的百分比

时间:2014-02-23 20:13:45

标签: ios objective-c uiimageview uiimage

我有一个名为UIImageView的{​​{1}}:

bigBottle

bigBottle.image = [UIImage imageNamed:@"fullBootle.png"]; 是一个装满100%的瓶子。

我需要两个步骤:

  1. 首先用百分比制作一幅图像(假设50%填充) - 也就是说,从底部中填充一半的瓶子。
  2. 动画fullBootle.png使填充效果从瓶子下方爬到50%填充。 我的代码如下:

    bigBottle
  3. 另一种方法是让这个灌装瓶子的动画更简单,更节省内存?我有几十瓶随机填充百分比(让我们说瓶子80填满了20%)并且没有模糊的结果图像?

2 个答案:

答案 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 
相关问题