新建一个类 继承于UIView
.h文件如下
#import <UIKit/UIKit.h>
@interface WQChatImgaView : UIView
/**
* 给外部提供一个image属性
*/
@property (nonatomic, strong) UIImage *image;
@end
.m实现如下
#import "WQChatImgaView.h"
@implementation WQChatImgaView
{
CALayer *_contentLayer;
CAShapeLayer *_maskLayer;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (void)setup
{
_maskLayer = [CAShapeLayer layer];
_maskLayer.fillColor = [UIColor blackColor].CGColor;
_maskLayer.strokeColor = [UIColor clearColor].CGColor;
_maskLayer.frame = self.bounds;
_maskLayer.contentsCenter = CGRectMake(0.5, 0.5, 0.1, 0.1);
//非常关键设置自动拉伸的效果且不变形
_maskLayer.contentsScale = [UIScreen mainScreen].scale;
_maskLayer.contents = (id)[UIImage imageNamed:@"chat_send_nor@2x"].CGImage;
_contentLayer = [CALayer layer];
_contentLayer.mask = _maskLayer;
_contentLayer.frame = self.bounds;
[self.layer addSublayer:_contentLayer];
}
- (void)setImage:(UIImage *)image
{
_contentLayer.contents = (id)image.CGImage;
}
@end
在控制器中的使用
#import "ViewController.h"
#import "WQChatImgaView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1.直接初始化
WQChatImgaView *shapedImageView = [[WQChatImgaView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
// 2.设置imgage
shapedImageView.image = [UIImage imageNamed:@"u=2366071268,3648144310&fm=58"];
[self.view addSubview:shapedImageView];
}
@end
最终实现效果如下
总结:只需两张图片即可完全自定义实现特殊轮廓的图片。