I'm trying to add a dashed border using CALayer
on a UIImageView
. I've found a method, but is that working in swift and how can i convert it to swift? o have another imageView which has a border so would be the best solution to use CALayer
, so they look similar? How can i obtain this
obj-c code to swift?
- (CAShapeLayer *) addDashedBorderWithColor: (CGColorRef) color {
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGSize frameSize = self.size;
CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height);
[shapeLayer setBounds:shapeRect];
[shapeLayer setPosition:CGPointMake( frameSize.width/2,frameSize.height/2)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
[shapeLayer setStrokeColor:color];
[shapeLayer setLineWidth:5.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:10],
[NSNumber numberWithInt:5],
nil]];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0];
[shapeLayer setPath:path.CGPath];
return shapeLayer;
}
Ok, I would do simply like this in the custom view class:
Updated for Swift 4
class DashedBorderView: UIView {
let _border = CAShapeLayer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
init() {
super.init(frame: .zero)
setup()
}
func setup() {
_border.strokeColor = UIColor.black.cgColor
_border.fillColor = nil
_border.lineDashPattern = [4, 4]
self.layer.addSublayer(_border)
}
override func layoutSubviews() {
super.layoutSubviews()
_border.path = UIBezierPath(roundedRect: self.bounds, cornerRadius:10).cgPath
_border.frame = self.bounds
}
}
Make an attempt to convert the code to Swift first. If you have problems, post the problem you are having.
I'll get you started:
func addDashedBorderWithColor(color: UIColor) -> CAShapeLayer {
let shapeLayer = CAShapeLayer()
let frameSize = self.bounds.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
//...
Updated for Swift 3:
if you want to make your ImageView/ UIView/ UILabel / UITextField as dashed border then used below simple lines of code;
func makeDashedBorder() {
let mViewBorder = CAShapeLayer()
mViewBorder.strokeColor = UIColor.magenta.cgColor
mViewBorder.lineDashPattern = [2, 2]
mViewBorder.frame = mYourAnyTypeOfView.bounds
mViewBorder.fillColor = nil
mViewBorder.path = UIBezierPath(rect: mYourAnyTypeOfView.bounds).cgPath
mYourAnyTypeOfView.layer.addSublayer(mViewBorder)
}
// Note : where, mYourAnyTypeOfView = UIView/ UIImageView/ UILabel/ UITextField and etc.
// Enjoy coding..!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.