【问题标题】:Setting multiple borders on UIView在 UIView 上设置多个边框
【发布时间】:2013-09-16 14:41:58
【问题描述】:
由于我找不到任何问题/答案,我想这是不可能的。
无论如何要在UIView 上设置多个边框。
我目前正在使用.layer.borderWidth 和layer.borderColor 设置标准边框。我想知道是否可以向视图添加多个笔触/边框效果。
我需要一个 4.0f 的白色边框,然后是另一个 1.0f 的另一种颜色。
【问题讨论】:
标签:
ios
ios6
uiview
uikit
quartz-graphics
【解决方案1】:
我能想到的三个解决方案:
- 将一个 UIView 嵌套在另一个 UIView 中,为每个定义一个边框;
- 在
-(void)drawRect自己画边框;
- 使用带有可调整大小的
UIImageView;可拉伸的边框图像作为背景(性能方面的最佳解决方案)。
【解决方案2】:
在不添加层的情况下使用单个 UIView 实例是不可能的。
您可以做的是创建一个大于所需的视图,适当地设置其边框,然后添加CALayer 并将其放置在您想要内边框的位置并适当地设置其边框属性。
使用CALayers 通常比完整的UIView 更快,但您也可以只使用嵌套的UIView 来达到相同的效果。
【解决方案3】:
您可以使用此扩展插入两个不同宽度的图层:
extension CALayer {
func addGradientBorder(colors:[UIColor],width:CGFloat = 1) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = CGRect(origin: CGPoint.zero, size: self.bounds.size)
gradientLayer.startPoint = CGPoint(x:0.0, y:0.0)
gradientLayer.endPoint = CGPoint(x:1.0,y:1.0)
gradientLayer.colors = colors.map({$0.cgColor})
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = width
shapeLayer.path = UIBezierPath(rect: self.bounds).cgPath
shapeLayer.fillColor = nil
shapeLayer.strokeColor = UIColor.red.cgColor
gradientLayer.mask = shapeLayer
self.addSublayer(gradientLayer)
}
}
使用不同的宽度/颜色来获得所需的效果:
yourView.layer.addGradientBorder(colors:[UIColor.black,UIColor.black] , width: 20)
yourView.layer.addGradientBorder(colors:[UIColor.white,UIColor.white] , width: 10)
输出如下图所示,外框为白色,内框为黑色:
【解决方案4】:
这是不可能的,您必须通过在 xib/view 中添加带有背景颜色的 UIView 来伪造边框。
【解决方案5】:
试试这个,
我正在添加带有 alpha 1 的阴影,它将充当内部边框。并且正常的边框被指定为外边框。
yourView.frame = CGRectInset(yourView.frame, -borderWidth, -borderWidth);
yourView.layer.borderColor = [UIColor blackColor].CGColor;
yourView.layer.borderWidth = borderWidth;
yourView.layer.shadowColor = [UIColor whiteColor].CGColor;
yourView.layer.shadowOffset = CGSizeMake(0, 1);
yourView.layer.shadowOpacity = 1;
yourView.layer.shadowRadius = 1.0;
yourView.clipsToBounds = YES;