美文网首页iOS开发_周边
将文字和图片合成到一张图上

将文字和图片合成到一张图上

作者: lucky_frank | 来源:发表于2019-04-12 19:10 被阅读0次
    @implementation UIButton (Utilities)
    
    - (instancetype _Nullable )secondLevelButtonWithIcon:(NSString *)icon IconSize:(CGSize)iconSize Frame:(CGRect)frame Title:(NSString *)title TitleColor:(UIColor*)titleColor Font:(CGFloat)font SpaceHeigt:(CGFloat)spaceHeight{
        UIImage * pictureImage = [UIImage imageNamed:icon];
        CGSize size = frame.size;
        //获取当前上下文
        UIGraphicsBeginImageContextWithOptions(size, false, [UIScreen mainScreen].scale);
        [[UIColor whiteColor] setFill];
        UIRectFill(CGRectMake(0, 0, size.width, size.height));
        //写入图片
        [pictureImage drawInRect:CGRectMake((size.width - iconSize.width) * 0.5, 0 , iconSize.width, iconSize.height)];
        //写入文字
        UILabel * label = [[UILabel alloc]init];
        label.text = title;
        label.textColor = titleColor;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:font];
        [label drawTextInRect:CGRectMake(0, iconSize.height+spaceHeight, size.width, font+1)];
        //生成图片
        UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //将映射的图片生成一个按钮
        UIButton * button  = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [button setBackgroundImage:image forState:UIControlStateHighlighted];
        button.frame = frame;
        return button;
    }
    
    @end
    
    

    相关文章

      网友评论

        本文标题:将文字和图片合成到一张图上

        本文链接:https://www.haomeiwen.com/subject/nkehwqtx.html