问题
I'm calling a function that sets up a UIImageView:
func setupImageView(_ imageView: UIImageView) {}
I want to give that UIImageView an image, round its corners, and give it two different borders.
Here is what I am currently doing:
imageView.image = imageConstants.imageThatIsWanted
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.layer.borderWidth = 3.0
imageView.layer.borderColor = UIColor.white.cgColor
What is the best way to apply a second borderColor of color blue around the white border?
I tried creating a sublayer as a CALayer and giving it a blue border, but this goes behind the image, and also inside of the white border. I also tried drawing a UIBezierPath, but that stays inside of the white border as well.
回答1:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var imgView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imgView.layer.cornerRadius = imgView.frame.size.height/2
secondView.layer.cornerRadius = secondView.frame.size.height/2
imgView.layer.borderWidth = 5.0
imgView.layer.borderColor = UIColor.red.cgColor
imgView.clipsToBounds = true
secondView.clipsToBounds = true
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
回答2:
You can add UIlabel or UIImageview at back of your image view having size little bit larger than your image view and applying corner radius, if you want to reduce line of your code (Please check below code)
imgview.layer.masksToBounds = true
imgview.layer.cornerRadius = imgview.frame.size.width/2
imgview.layer.borderWidth = 5
imgview.layer.borderColor = UIColor.white.cgColor
Add new image view programatically at back side of image view already taken
let img = UIImageView(frame: CGRect(x: imgview.frame.origin.x - 2, y: imgview.frame.origin.y - 2, width: imgview.frame.size.width + 4, height: imgview.frame.size.height + 4))
img.layer.masksToBounds = true
img.layer.cornerRadius = img.frame.size.width/2
//img.backgroundColor = UIColor.blue // You can also use background color instead of border
img.layer.borderWidth = 5
img.layer.borderColor = UIColor.blue.cgColor
self.view.addSubview(img)
self.view.sendSubview(toBack: img)
I know its not proper solution but we can use this to reduce lines of code Hope it will helps you
来源:https://stackoverflow.com/questions/47703742/image-view-double-border