2014-10-19 64 views
6

我想在UIImageView上使用CALayer添加虛線邊框。我找到了一種方法,但它是在迅速工作,我如何將它轉換爲快速? o另一個具有邊框的imageView將是使用CALayer的最佳解決方案,所以它們看起來相似?我如何獲得這個虛線邊界UIImageView swift

obj-c代碼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; 
} 

回答

19

好吧,我會做簡單的像這樣的自定義視圖類:

class DashedBorderView: UIView { 

    let _border = CAShapeLayer() 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
     setup() 
    } 

    init() { 
     super.init(frame: CGRectZero) 
     setup() 
    } 

    func setup() { 
     _border.strokeColor = UIColor.whiteColor().CGColor 
     _border.fillColor = nil 
     _border.lineDashPattern = [4, 4] 
     self.layer.addSublayer(_border) 
    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 
     _border.path = UIBezierPath(roundedRect: self.bounds, cornerRadius:8).CGPath 
     _border.frame = self.bounds 
    } 
} 
+0

感謝@jsiodtb添加該行。 – 2015-03-18 10:07:43

+0

這對我有用!謝謝 – 2015-05-14 15:48:50

+0

精美的作品,我編輯了一下,使它更通用。非常感謝! – n13 2016-02-15 01:42:49

0

嘗試先將代碼轉換爲Swift。如果您遇到問題,請發佈您遇到的問題。

我會得到你開始:

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

更新了斯威夫特3:

如果你想讓你的ImageView/UIView/UILabel/UITextField爲虛線邊框,然後在簡單的線條下使用o f代碼;

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) 
} 

//注:其中,mYourAnyTypeOfView =的UIView /的UIImageView /的UILabel /的UITextField等

//享受編碼..!