源码0308-模仿UIImageView

//  ViewController.m
//  08-模仿UIImageView
#import "ViewController.h"

#import "XMGImageView.h"

@interface ViewController ()

@property (nonatomic, strong) XMGImageView *imageV;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
//    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 350)];
    
    // 默认控件的尺寸跟图片一样
//    UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"汽水"]];
//    imageV.image = [UIImage imageNamed:@"汽水"];
    
    
//    _imageV = imageV;
    
    
    // 默认图片把控件填充,图片的尺寸跟控件尺寸一样大
//    [self.view addSubview:imageV];
    
//    XMGImageView *imageView = [[XMGImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 350)];
//    _imageV = imageView;
   XMGImageView *imageView = [[XMGImageView alloc] initWithImage:[UIImage imageNamed:@"汽水"]];
//    imageView.image = [UIImage imageNamed:@"汽水"];
//    
    [self.view addSubview:imageView];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _imageV.image = [UIImage imageNamed:@"CTO"];
}

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

@end
//  XMGImageView.h
//  08-模仿UIImageView

#import <UIKit/UIKit.h>

@interface XMGImageView : UIView

@property (nonatomic, strong) UIImage *image;
- (instancetype)initWithImage:(UIImage *)image;
@end
//  XMGImageView.m
//  08-模仿UIImageView
#import "XMGImageView.h"

@implementation XMGImageView

- (instancetype)initWithImage:(UIImage *)image
{
    // 默认跟图片尺寸一样大
    if (self = [super initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)]) {
        
        _image = image;
    }
    
    return self;
}

- (void)setImage:(UIImage *)image
{
    _image = image;
    
    [self setNeedsDisplay];
}

// 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];
}


@end
本人无商业用途,仅仅是学习做个笔记,特别鸣谢小马哥,学习了IOS,另日语学习内容有需要文本和音频请关注公众号:riyuxuexishuji
原文地址:https://www.cnblogs.com/laugh/p/6677546.html