首页 > 代码库 > 重写UIImageView的image属性---

重写UIImageView的image属性---

 

效果:

 

 

当你重写了UIImageView的image属性后你就会对UIImageView怎么显示图片了如指掌了:

源码:

UIImageView.h  +  UIImageView.m

////  LiveImageView.h//  Progress////  Copyright (c) 2014年 L.S. All rights reserved.//#import <UIKit/UIKit.h>@interface LiveImageView : UIImageView@property (nonatomic, assign)  CGFloat  duration;@end
////  LiveImageView.m//  Progress////  Copyright (c) 2014年 L.S. 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 = http://www.mamicode.com/(__bridge id)(_image.CGImage);        ani.toValue   =  http://www.mamicode.com/(__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,赋值都是没有显式动画的.

 

//  LRootViewController.m//  UIImageTest//  Copyright (c) 2014年 L.S. All rights reserved.//#import "LRootViewController.h"#import "LiveImageView.h"@interface LRootViewController (){    NSArray *_imageArray;    LiveImageView *liveView;     __block int count;}@end@implementation LRootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (void)viewDidLoad{    [super viewDidLoad];    _imageArray=[NSArray arrayWithObjects:[UIImage imageNamed:@"33.jpg"],[UIImage imageNamed:@"44.jpg"],[UIImage imageNamed:@"66.jpg"],nil];        liveView=[[LiveImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];    [self.view addSubview:liveView];    liveView.center=self.view.center;    NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];    [timer fire];    }-(void)changeImage{       //改变图片    [UIView animateWithDuration:0.3f animations:^{        liveView.duration=0.3f;        liveView.image=_imageArray[count++%3];//count++%4这是循环取数组中的对象        //改变尺寸的效果        CGRect tmpRect=liveView.bounds;        tmpRect.size = liveView.image.size;        liveView.bounds=tmpRect;        liveView.center=self.view.center;            }];}

 

以下地方是改变尺寸的动画代码