博客> iOS之拉伸填充图片
iOS之拉伸填充图片
2017-10-19 07:02 评论:0 阅读:405 OS_JJ
ios 拉伸填充图片
1.首先创建按钮并对按钮设置 contentEdgeInsets 属性
     self.textBtn.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
2.获取按钮和按钮中文字的 frame

    //frame方法
    - (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize{
        NSDictionary *attr = @{NSFontAttributeName : font};
        return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attr context:nil].size;
    }

    //调用frame方法
    CGSize textSize = [self sizeWithText:message.text font:MNTextFont maxSize:CGSizeMake(200, MAXFLOAT)];
if (message.type == MNMessageTypeOther) {
    _textF =  CGRectMake(CGRectGetMaxX(_iconF) + 10, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
}else{
    _textF =  CGRectMake(screenW-10-40-10-textSize.width-40, CGRectGetMaxY(_timeF)+15, textSize.width+40, textSize.height+40);
}

3.拉伸填充
    - (UIImage *)resizableImageWithCapInsets:(NSString *)name{
        UIImage *normal = [UIImage imageNamed:name];
        CGFloat normaiW = normal.size.width * 0.5;
        CGFloat normaiH = normal.size.height *0.5;
        return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(normaiH, normaiW, normaiH, normaiW)];
}        

例子: if (message.type == MNMessageTypeMe) { [self.textBtn setBackgroundImage:[self resizableImageWithCapInsets:@"chat_send_nor"] forState:UIControlStateNormal]; }else{ [self.textBtn setBackgroundImage:[self resizableImageWithCapInsets:@"chat_recive_nor"] forState:UIControlStateNormal]; }

分类中封装 1.创建分类文件 UIImage+Extension.h/UIImage+Extension.h 2.在UIImage+Extension.h中创建方法

  • (UIImage )resizableImageWithCapInsets:(NSString )name; 3.实现该方法
  • (UIImage )resizableImageWithCapInsets:(NSString )name{ UIImage normal = [UIImage imageNamed:name]; CGFloat normaiW = normal.size.width 0.5; CGFloat normaiH = normal.size.height *0.5; return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(normaiH, normaiW, normaiH, normaiW)]; }

例子: if (message.type == MNMessageTypeMe) { [self.textBtn setBackgroundImage:[UIImage resizableImageWithCapInsets:@"chat_send_nor"] forState:UIControlStateNormal]; }else{ [self.textBtn setBackgroundImage:[UIImage resizableImageWithCapInsets:@"chat_recive_nor"] forState:UIControlStateNormal]; }

收藏
0
sina weixin mail 回到顶部