iOS技术点

iOS 气泡/多边形等自定制形状和颜色的背景图(继承自UIIma

2017-03-31  本文已影响159人  90de46ea2b08

在做IM即时通讯时候,聊天内容需要有气泡背景,今天单独把这个类拿出来写一下(不仅支持气泡形状的,各种形状和颜色都ok的哈!),很简单,直接上代码,写得不好或者有问题直接评论或者关注私信,有问必回哈😄

BubbleBgView.h

#import <UIKit/UIKit.h>

@interface BubbleBgView : UIImageView
{
  CALayer      *_contentLayer;
  CAShapeLayer *_maskLayer;
}
//设置图层形状并用图片填充图层
- (void)setContentLayerContentsWithImage:(UIImage *)contentImage AndFillBackgroundImage:(UIImage *)bgImage;

//设置图层形状并用颜色填充图层
- (void)setContentLayerContentsWithImage:(UIImage *)contentImage AndFillBackgroundColor:(UIColor *)bgColor;
@end

BubbleBgView.m

#import "BubbleBgView.h"

@implementation BubbleBgView
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [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; //非常关键设置自动拉伸的效果且不变形
    _contentLayer = [CALayer layer];
    _contentLayer.mask = _maskLayer;
    _contentLayer.frame = self.bounds;
    [self.layer addSublayer:_contentLayer];
}
//设置图层形状并用图片填充图层
- (void)setContentLayerContentsWithImage:(UIImage *)contentImage AndFillBackgroundImage:(UIImage *)bgImage
{
    _maskLayer.contents = (id)contentImage.CGImage;//这里的图片形状决定图层的形状
    _contentLayer.contents = (id)bgImage.CGImage;
}

//设置图层形状并用颜色填充图层
- (void)setContentLayerContentsWithImage:(UIImage *)contentImage AndFillBackgroundColor:(UIColor *)bgColor
{
    _maskLayer.contents = (id)contentImage.CGImage;//这里的图片形状决定图层的形状
    _contentLayer.backgroundColor = bgColor.CGColor;
}
@end

使用

#import "BubbleBgView.h"



BubbleBgView *bgView = [[BubbleBgView alloc]initWithFrame:CGRectMake(100, 100, 200, 80)];
    [self.view addSubview:bgView];

     /*
     参数一:图片形状决定图层可显示区域形状
     参数二:决定填充图层的内容
     */
    //设置图层形状并用图片填充图层
//    [bgView setContentLayerContentsWithImage:[UIImage imageNamed:@"bubble.png"] AndFillBackgroundImage:[UIImage imageNamed:@"1.png"]];
    //设置图层形状并用颜色填充图层
    [bgView setContentLayerContentsWithImage:[UIImage imageNamed:@"bubble.png"] AndFillBackgroundColor:[UIColor redColor]];
上一篇下一篇

猜你喜欢

热点阅读