我试图在UIImageView上使用CALayer添加虚线边框。我找到了一种方法,但是它在swift中工作,我怎样才能将它转换为swift? o有另一个带有边框的imageView,这将是使用CALayer的最佳解决方案,所以它们看起来相似吗?我怎样才能获得这个
快速的obj-c代码?
- (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;
}
答案 0 :(得分:24)
好的,我会在自定义视图类中执行此操作:
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
}
}
答案 1 :(得分: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
//...
答案 2 :(得分:0)
针对Swift 3进行了更新:
如果你想让你的ImageView / UIView / UILabel / UITextField成为虚线边框,那么在简单的代码行下使用;
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等
//享受编码..!