如何在UIImageView中创建多色边框?

时间:2017-10-03 07:50:30

标签: ios swift uiimageview

我希望实现Imageview喜欢 -

enter image description here

到目前为止,我正在使用:

roundedImage.layer.cornerRadius = roundedImage.frame.width/2
        roundedImage.layer.masksToBounds = true
        roundedImage.layer.borderWidth = 2.0
        roundedImage.layer.borderColor = UIColor.red.cgColor

但它给了我

enter image description here

如何完成多色圆形边框?

3 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个用渐变色的圆形背景视图,并将imageView放在顶部,带有1px白色边框

答案 1 :(得分:1)

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.roundedImage.frame.size)
    gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]

    let shape = CAShapeLayer()
    shape.lineWidth = 2
    shape.path = UIBezierPath(rect: roundedImage.bounds).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    roundedImage.layer.addSublayer(gradient)

答案 2 :(得分:0)

尝试为CALayer 创建扩展程序。

  

它也适用于其他地方的应用程序。

我将颜色设置为红色和粉红色。请根据需要调整其他值

目标C:

@implementation CALayer(Border)

-(void) addGradientBorderColor {
    CAGradientLayer *objgradientLayer =  [[CAGradientLayer alloc] init];
    objgradientLayer.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    objgradientLayer.startPoint = CGPointMake(0.0, 0.5);
    objgradientLayer.endPoint = CGPointMake(1.0, 0.5);
    objgradientLayer.colors = @[(id)[UIColor redColor].CGColor, (id)
    [UIColor colorWithRed:(255/255.0) green:(192/255.0) blue:(203/255.0) alpha:1].CGColor];

    CAShapeLayer *objShapeLayer =[[CAShapeLayer alloc] init];
    objShapeLayer.lineWidth = 0.5;
    objShapeLayer.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
    objShapeLayer.fillColor = nil;
    objShapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    objgradientLayer.mask = objShapeLayer;

    [self addSublayer : objgradientLayer];
}

@end

斯威夫特:

extension CALayer {
    func addGradienBorder(colors:[UIColor] = [UIColor.redColor().CGColor,UIColor(red: 255/255, green: 192/255, blue: 203/255, alpha: 1).CGColor],width:CGFloat = 1) {
        let objgradientLayer = CAGradientLayer()
        objgradientLayer =  CGRect(origin: CGPointZero, size: self.bounds.size)
        objgradientLayer = CGPointMake(0.0, 0.5)
        objgradientLayer = CGPointMake(1.0, 0.5)
        objgradientLayer = colors.map({$0.CGColor})

        let objShapeLayer = CAShapeLayer()
        objShapeLayer.lineWidth = 1
        objShapeLayer.path = UIBezierPath(rect: self.bounds).CGPath
        objShapeLayer.fillColor = UIColor.clear.cgColor
        objShapeLayer.strokeColor = UIColor.blackColor().CGColor
        objgradientLayer.mask = objShapeLayer

        self.addSublayer(objgradientLayer)
    }
}

希望有所帮助!