Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dashed border UIImageView swift

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;
}
like image 988
Peter Pik Avatar asked Oct 19 '14 00:10

Peter Pik


People also ask

How do I add a dashed border in Swift?

To use this, call the addDashedBorder() on your view. You can use the same extension on UILabel or almost any view. That's all on how to add dashed line border around UIView. Learn how to add animations to your SwiftUi app here!

How do I add actions to Uiimageview?

Open the Library, look for "Tap Gesture Recognizer" object. Drag the object to your storyboard, and set the delegate to the image you want to trigger actions. Then go to the view controller, drag the same object to set the IBAction.


1 Answers

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
    }
}
like image 84
Goon Nguyen Avatar answered Oct 24 '22 20:10

Goon Nguyen