首页 > 代码库 > 重写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; }];}
以下地方是改变尺寸的动画代码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。