UIImageView swift dotted border

I am trying to add a dashed border using CALayer in a UIImageView. I found a method, but it works fast and how can I convert it to fast? o having another image that has a border would be the best solution to use CALayer, so they look the same? How can i get this

obj-c code for quick?

- (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; } 
+7
source share
3 answers

Ok, I would just do this in a 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 } } 
+24
source

Try to convert the code to Swift first. If you have a problem, submit the problem you have.

I will make you start:

 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 //... 
0
source

Updated for Swift 3:

if you want to make your ImageView / UIView / UILabel / UITextField a dashed border, then be used under 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, etc.

// Enjoy the coding ..!

0
source

Source: https://habr.com/ru/post/976920/


All Articles