重写UIImageView的image属性
效果:
当你重写了UIImageView的image属性后你就会对UIImageView怎么显示图片了如指掌了:)
源码:
UIImageView.h + UIImageView.m
// // LiveImageView.h // Progress // // Copyright (c) 2014年 Y.X. All rights reserved. // #import <UIKit/UIKit.h> @interface LiveImageView : UIImageView @property (nonatomic, assign) CGFloat duration; @end
// // LiveImageView.m // Progress // // Copyright (c) 2014年 Y.X. All rights reserved. // #import "LiveImageView.h" @interface LiveImageView () { CALayer *_Layer; } @end @implementation LiveImageView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _duration = 0.3f; _Layer = self.layer; } return self; } // 重写image的setter与getter方法 @synthesize image = _image; - (void)setImage:(UIImage *)image { if (_image != image) { CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"contents"]; ani.fromValue = (__bridge id)(_image.CGImage); ani.toValue = (__bridge id)(image.CGImage); ani.duration = _duration; _Layer.contents = (__bridge id)(image.CGImage); [_Layer addAnimation:ani forKey:nil]; _image = image; } } - (UIImage *)image { return _image; } @end
以下是核心代码:
系统的setter方法绝对是这么写的哦:),亲自测试,因为是backed layer,赋值都是没有显式动画的.
以下地方是改变尺寸的动画代码