我试图使用CALayer在UIImageView上添加虚线边框。我已经找到了一种方法,但这是在快速工作,我如何才能把它转换为斯威夫特呢?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;
}发布于 2014-11-19 03:13:01
好的,我会在定制视图类中这样做:
为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
}
}发布于 2014-10-19 00:40:46
尝试先将代码转换为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
//...发布于 2017-09-12 06:54:57
更新为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)
}// Note : where,mYourAnyTypeOfView = UIView/ UIImageView/ UILabel/ UITextField等等
//享受编码..!
https://stackoverflow.com/questions/26445894
复制相似问题