ios UIView 周围的虚线边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13679923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dashed line border around UIView
提问by Sohaib
How do I add dashed line border around UIView
.
如何在UIView
.
Something Like this
像这样的东西
采纳答案by Paras Joshi
You can set the border with this pattern using Layer and Bezier path like below examples.
您可以使用图层和贝塞尔路径使用此模式设置边框,如下例所示。
Objective-C
目标-C
CAShapeLayer *yourViewBorder = [CAShapeLayer layer];
yourViewBorder.strokeColor = [UIColor blackColor].CGColor;
yourViewBorder.fillColor = nil;
yourViewBorder.lineDashPattern = @[@2, @2];
yourViewBorder.frame = yourView.bounds;
yourViewBorder.path = [UIBezierPath bezierPathWithRect:yourView.bounds].CGPath;
[yourView.layer addSublayer:yourViewBorder];
Swift 3.1
斯威夫特 3.1
var yourViewBorder = CAShapeLayer()
yourViewBorder.strokeColor = UIColor.black.cgColor
yourViewBorder.lineDashPattern = [2, 2]
yourViewBorder.frame = yourView.bounds
yourViewBorder.fillColor = nil
yourViewBorder.path = UIBezierPath(rect: yourView.bounds).cgPath
yourView.layer.addSublayer(yourViewBorder)
You can also set different types of design using pattern image like below example.
您还可以使用图案图像设置不同类型的设计,如下例所示。
[yourView.layer setBorderWidth:5.0];
[yourView.layer setBorderColor:[[UIColor colorWithPatternImage:[UIImage imageNamed:@"DotedImage.png"]] CGColor]];///just add image name and create image with dashed or doted drawing and add here
Here you've to add <QuartzCore/QuartzCore>
framework in the project and import it with below line in YourViewController.m
file.
在这里,您必须<QuartzCore/QuartzCore>
在项目中添加框架并在YourViewController.m
文件中使用以下行导入它。
#import <QuartzCore/QuartzCore.h>
回答by Chris
Another method if you like sublayers. In your custom view's init, put this (_border is an ivar):
如果你喜欢子层,另一种方法。在您的自定义视图的 init 中,输入以下内容(_border 是一个 ivar):
_border = [CAShapeLayer layer];
_border.strokeColor = [UIColor colorWithRed:67/255.0f green:37/255.0f blue:83/255.0f alpha:1].CGColor;
_border.fillColor = nil;
_border.lineDashPattern = @[@4, @2];
[self.layer addSublayer:_border];
And in your layoutsubviews, put this:
在你的布局子视图中,把这个:
_border.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
_border.frame = self.bounds;
回答by rmooney
For those of you working in Swift, this class extension on UIView makes it easy. This was based on sunshineDev's answer.
对于那些在 Swift 中工作的人来说,UIView 上的这个类扩展很容易。这是基于sunnyDev的回答。
extension UIView {
func addDashedBorder() {
let color = UIColor.red.cgColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 2
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineDashPattern = [6,3]
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath
self.layer.addSublayer(shapeLayer)
}
}
To use it:
要使用它:
anyView.addDashedBorder()
回答by sash
Swift 3:
斯威夫特 3:
import UIKit
class UIViewWithDashedLineBorder: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: 0)
UIColor.purple.setFill()
path.fill()
UIColor.orange.setStroke()
path.lineWidth = 5
let dashPattern : [CGFloat] = [10, 4]
path.setLineDash(dashPattern, count: 2, phase: 0)
path.stroke()
}
}
Use in a storyboard (as custom class) or directly in code:
在故事板中使用(作为自定义类)或直接在代码中使用:
let v = UIViewWithDashedLineBorder(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
Result:
结果:
回答by sunshineDev
Building upon what Prasad G has suggested I created a method inside a UIImage Extras class with the following:
基于 Prasad G 的建议,我在 UIImage Extras 类中创建了一个方法,如下所示:
- (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;
}
It's important to point out that if you define your shape's position as (0,0), the bottom corner of the border will be placed in the center of the image, that's why I set it to: (frameSize.width/2,frameSize.height/2)
需要指出的是,如果您将形状的位置定义为 (0,0),则边框的底角将位于图像的中心,这就是我将其设置为:(frameSize.width/2,frameSize .高度/2)
I then use my method to get the dashed border using the UIImage of my UIImageView and add the CAShapeLayer as a sublayer of the UIImageView layer:
然后我使用我的方法使用我的 UIImageView 的 UIImage 获取虚线边框,并将 CAShapeLayer 添加为 UIImageView 层的子层:
[myImageView.layer addSublayer:[myImageView.image addDashedBorderWithColor:[[UIColor whiteColor] CGColor]]];
回答by Prasad G
Use CGContextSetLineDash() method.
使用 CGContextSetLineDash() 方法。
CGFloat dashPattern[]= {3.0, 2};
context =UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
// And draw with a blue fill color
CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
// Draw them with a 2.0 stroke width so they are a bit more visible.
CGContextSetLineWidth(context, 4.0);
CGContextSetLineDash(context, 0.0, dashPattern, 2);
CGContextAddRect(context, self.bounds);
// Close the path
CGContextClosePath(context);
CGContextStrokePath(context);
// Fill & stroke the path
CGContextDrawPath(context, kCGPathFillStroke);
I think it will be helpful to you.
我想它会对你有所帮助。
回答by btmanikandan
For this you need add CAShapeLayer for that particular object
为此,您需要为该特定对象添加 CAShapeLayer
CAShapeLayer * dotborder = [CAShapeLayer layer];
dotborder.strokeColor = [UIColor redColor].CGColor;//your own color
dotborder.fillColor = nil;
dotborder.lineDashPattern = @[@4, @2];//your own patten
[codeBtn.layer addSublayer:dotborder];
dotborder.path = [UIBezierPath bezierPathWithRect:codeBtn.bounds].CGPath;
dotborder.frame = codeBtn.bounds;
回答by xavi.pedrals
Here is a UIView subclass that can work for any project, it also works for roundviews:
这是一个适用于任何项目的 UIView 子类,它也适用于圆形视图:
import UIKit
class CustomDashedView: UIView {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var dashWidth: CGFloat = 0
@IBInspectable var dashColor: UIColor = .clear
@IBInspectable var dashLength: CGFloat = 0
@IBInspectable var betweenDashesSpace: CGFloat = 0
var dashBorder: CAShapeLayer?
override func layoutSubviews() {
super.layoutSubviews()
dashBorder?.removeFromSuperlayer()
let dashBorder = CAShapeLayer()
dashBorder.lineWidth = dashWidth
dashBorder.strokeColor = dashColor.cgColor
dashBorder.lineDashPattern = [dashLength, betweenDashesSpace] as [NSNumber]
dashBorder.frame = bounds
dashBorder.fillColor = nil
if cornerRadius > 0 {
dashBorder.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
} else {
dashBorder.path = UIBezierPath(rect: bounds).cgPath
}
layer.addSublayer(dashBorder)
self.dashBorder = dashBorder
}
}
This way you can edit from the Storyboard like this:
通过这种方式,您可以像这样从 Storyboard 进行编辑:
A pair of results:
一对结果:
回答by Robert Chen
Swift version of the QuartzCore answer.
QuartzCore 答案的 Swift 版本。
import QuartzCore
let dottedPattern = UIImage(named: "dottedPattern")
myView.layer.borderWidth = 1
myView.layer.borderColor = UIColor(patternImage: dottedPattern!).CGColor
The CAShapeLayer
approach works, but the QuartzCore approach is better at handling a Table View reload, if the UIView
is inside a cell.
该CAShapeLayer
方法有效,但 QuartzCore 方法更擅长处理表视图重新加载,如果UIView
它在单元格内。
For the image, you can use something like this (it's really small):
对于图像,你可以使用这样的东西(它真的很小):
I tend to prefer vector over PNGs when I can get away with it:
当我可以摆脱它时,我倾向于更喜欢矢量而不是 PNG:
- Within Sketch, create a 4x4 pixel rectangle.
- Make a total of four of these
- Group them into a foursquare, alternating colors
- Export the group as PDF
- Within
Images.xcassets
, create aNew Image Set
called dottedPattern - Change the
Scale Factors
toSingle Vector
- Drop in your PDF
- 在 Sketch 中,创建一个 4x4 像素的矩形。
- 总共做这四个
- 将它们组合成一个四方形,交替的颜色
- 将组导出为 PDF
- 在 中
Images.xcassets
,创建一个New Image Set
名为 dottedPattern - 更改
Scale Factors
为Single Vector
- 放入您的 PDF
回答by c.lamont.dev
For Xamarin.iOS dashed/dotted border.
对于 Xamarin.iOS 虚线/虚线边框。
dottedLayer = new CAShapeLayer();
dottedLayer.StrokeColor = UIColor.FromRGB(202, 202, 208).CGColor;
dottedLayer.FillColor = null;
dottedLayer.LineDashPattern = new[] { new NSNumber(4), new NSNumber(2) };
dottedLayer.Path = UIBezierPath.FromRect(YourView.Bounds).CGPath; //for square
dottedLayer.Path = UIBezierPath.FromRoundedRect(YourView.Bounds, 5).CGPath; //for rounded corners
dottedLayer.Frame = YourView.Bounds;
YourView.Layer.AddSublayer(dottedLayer);