iOS—实现UI imageview的底层

新建一个类 HM imageView 类似于系统自带的UI imageview 效果是一样的 

//
//  HMUIimageView.h
//  模仿imageView的底层实现
//
//  Created by YaguangZhu on 15/9/9.
//  Copyright (c) 2015年 YaguangZhu. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface HMUIimageView : UIView
@property (nonatomic,strong)UIImage *image;
@end

//
//  HMUIimageView.m
//  模仿imageView的底层实现
//
//  Created by YaguangZhu on 15/9/9.
//  Copyright (c) 2015年 YaguangZhu. All rights reserved.
//

#import "HMUIimageView.h"

@implementation HMUIimageView



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    
    // Drawing code
    [_image drawInRect:rect];
}

- (void)setImage:(UIImage *)image
{
    _image = image;
    [self setNeedsDisplay];
}
@end
//
//  ViewController.m
//  模仿imageView的底层实现
//
//  Created by YaguangZhu on 15/9/9.
//  Copyright (c) 2015年 YaguangZhu. All rights reserved.
//

#import "ViewController.h"
#import "HMUIimageView.h"
@interface ViewController ()
{
    HMUIimageView *_imgV;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
//    imgV.image = [UIImage imageNamed:@"liuyan"];
//    [self.view addSubview:imgV];
    
    HMUIimageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 250, 250)];
    imgV.image = [UIImage imageNamed:@"liuyan"];
    [self.view addSubview:imgV];
    _imgV = imgV;
    
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _imgV.image = [UIImage imageNamed:@"teacher"];
     
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/zhuyaguang/p/4795935.html