我想要一个带有黑色中心和彩色边框的圆形视图。当我设置我的观点时这样:
myView.backgroundColor = UIColor.red
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3
我只是一个红色的圆形。但是当我进入Debug View Hierarchy时,我看到myView有一个白色边框。疯狂!我做错了什么?
答案 0 :(得分:0)
您可以使用自定义边框和背景,如下面的
@IBDesignable class view_border_background: UIView {
private let gradientLayer : CAGradientLayer = CAGradientLayer()
//let gradientLayer = CAGradientLayer()
// IBInspectable properties for the gradient colors
@IBInspectable var bottomColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var middleColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var topColor: UIColor = UIColor(hex: 0xe5e5e5)
@IBInspectable var bottomColorAlpha: CGFloat = 1.0
@IBInspectable var middleColorAlpha: CGFloat = 1.0
@IBInspectable var topColorAlpha: CGFloat = 1.0
// IBInspectable properties for rounded corners and border color / width
@IBInspectable var cornerSize: CGFloat = 0
@IBInspectable var borderSize: CGFloat = 1
@IBInspectable var borderColor: UIColor = colorize(hex: 0x8bc218)
@IBInspectable var borderAlpha: CGFloat = 1.0
override func draw(_ rect: CGRect) {
// set up border and cornerRadius
self.layer.cornerRadius = cornerSize
self.layer.borderColor = borderColor.withAlphaComponent(borderAlpha).cgColor
self.layer.borderWidth = borderSize
self.layer.masksToBounds = true
// set up gradient
gradientLayer.frame = rect
let c1 = bottomColor.withAlphaComponent(bottomColorAlpha).cgColor
let c2 = middleColor.withAlphaComponent(middleColorAlpha).cgColor
let c3 = topColor.withAlphaComponent(topColorAlpha).cgColor
gradientLayer.colors = [c3, c2, c1]
gradientLayer.startPoint = CGPoint(x: 0, y: 0)
gradientLayer.endPoint = CGPoint(x: 0, y: 0)
self.layer.insertSublayer(gradientLayer, at: 0)
}
override public func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = self.layer.bounds
}
}
十六进制颜色转换
func colorize (hex: Int, alpha: Double = 1) -> UIColor {
let red = Double((hex & 0xFF0000) >> 16) / 255.0
let green = Double((hex & 0xFF00) >> 8) / 255.0
let blue = Double((hex & 0xFF)) / 255.0
var color: UIColor = UIColor( red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha:CGFloat(alpha) )
return color
}
只需添加" view_border_background"在VIView中展示身份检查员
答案 1 :(得分:0)
我测试了它,在我的模拟器中工作正常
override func viewDidLoad() {
super.viewDidLoad()
myView.layer.cornerRadius = myView.frame.size.width/2 //first make your view as rounded.
myView.layer.backgroundColor = UIColor.red.cgColor //convert into cgColor
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3
}