美文网首页ios
UIButton,UIView添加渐变边框

UIButton,UIView添加渐变边框

作者: 球球ol | 来源:发表于2020-12-17 16:49 被阅读0次

    思路参考
    举例UIButtom思路:
    1、 首先创建一个临时的 UIView
    2、 然后利用 CAGradientLayer 在 UIView 上面进行渐变绘制
    3、将UIView 进行截图返回 UIImage
    4、将返回的 UIImage 设置到 UIButton 的 setBackgroundImage
    这样就可以完成了一个UIButton 的渐变色 绘制,并且可以根据不用的颜色来设置Button UIControlStateNormal | UIControlStateHighlighted | UIControlStateDisabled 来进行设置效果。
    5、在已经绘制好有渐变色的UIView 上面盖多一个白色的 UIView 比 上面那个UIView 小一些像素 即可
    下面直接贴代码

    /**
     btnRect:按钮的frame
     borderWidth:按钮的边框宽度
     默认圆角为高度的1/2,修改圆角需要修改gradientLayer和whiteView的cornerRadius
     */
    - (UIImage *)getImageWithFrame:(CGRect)btnRect withBorderWidth:(CGFloat)borderWidth{
        CGFloat btnWidth = btnRect.size.width;
        CGFloat btnHeight = btnRect.size.height;
        //用来放置渐变色的view
        UIView *crView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btnWidth, btnHeight)];
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.colors = @[(__bridge id)[UIColor colorWithRed:1 green:172/255.0 blue:64/255.0 alpha:1].CGColor, (__bridge id)[UIColor colorWithRed:254/255.0 green:119/255.0 blue:119/255.0 alpha:1].CGColor];
        gradientLayer.locations = @[@0.3, @0.7];
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1.0, 0);
        gradientLayer.frame = CGRectMake(0, 0, crView.frame.size.width, crView.frame.size.height);
        gradientLayer.cornerRadius = btnHeight*1.0/2;
        [crView.layer addSublayer:gradientLayer];
        //空白view
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(borderWidth, borderWidth, btnWidth-borderWidth*2, btnHeight-borderWidth*2)];
        whiteView.layer.cornerRadius = btnHeight*1.0/2;
        whiteView.backgroundColor = [UIColor whiteColor];
        [crView addSubview:whiteView];
        //把配置好的view转变成image
        CGSize s = CGSizeMake(btnWidth, btnHeight);
        // 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
        UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
        [crView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
        
    }
    

    使用方法:

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 200, 200, 50);
        [btn setTitle:@"+关注" forState:UIControlStateNormal];
        [btn setBackgroundImage:[self getImageWithFrame:btn.frame withBorderWidth:0.5] forState:UIControlStateNormal];
        [self.view addSubview:btn];
    

    参考文档还写了渐变文字的方法,我尝试了下没成功,改天再看

    相关文章

      网友评论

        本文标题:UIButton,UIView添加渐变边框

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