UIView周围的虚线边界

Soh*_*aib 145 iphone objective-c uiview ios

如何添加虚线边框UIView.

像这样的东西

Chr*_*ris 270

另一种方法,如果你喜欢子层.在你的自定义视图的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];
Run Code Online (Sandbox Code Playgroud)

在你的布局子视图中,把它放在:

_border.path = [UIBezierPath bezierPathWithRect:self.bounds].CGPath;
_border.frame = self.bounds;
Run Code Online (Sandbox Code Playgroud)

  • 太好了!你也可以使用这样的东西来实现圆角效果:`_border.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:5.f] .CGPath;` (38认同)
  • 应该是选定的答案,IMO. (6认同)
  • 最简单永远是最好的 - 非常感谢 (3认同)
  • **Swift 3:** `border = CAShapeLayer() border.strokeColor = yourColor border.fillColor = nil border.lineDashPattern = [4, 2] self.layer.addSublayer(border)` (3认同)
  • @VanDuTran在第一个片段中,`_border.lineWidth = 3` (2认同)

Par*_*shi 123

您可以使用Layer和Bezier路径设置此模式的边框,如下例所示.

Objective-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];
Run Code Online (Sandbox Code Playgroud)

Swift 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)
Run Code Online (Sandbox Code Playgroud)

您还可以使用模式图像设置不同类型的设计,如下例所示.

[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
Run Code Online (Sandbox Code Playgroud)

在这里,您需要<QuartzCore/QuartzCore>在项目中添加框架并将其导入到YourViewController.m文件中的下一行.

#import <QuartzCore/QuartzCore.h>
Run Code Online (Sandbox Code Playgroud)

  • 什么是图像的例子? (5认同)
  • 在谈论iPhone6 plus时,这不是一个完美的方式.虚线可能变得模糊. (2认同)

rmo*_*ney 63

对于那些在Swift工作的人来说,UIView上的这个类扩展使它变得简单.这是基于sunshineDev的回答.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它:

anyView.addDashedBorder()
Run Code Online (Sandbox Code Playgroud)

  • 如果有人在“UITableViewCells”上得到不正确的 CGSize,我会通过在“contentView”上调用“layoutIfNeeded()”来修复它。 (4认同)
  • 我认为您可能太早调用 addDashBorder ,尝试在 didLayoutSubviews 内调用它 (3认同)
  • 我创建了一个自定义UIView并将此扩展名放入其中.然后我在`didMoveToSuperview()期间调用了`addDashedBorder()`,认为autolayout将在那时完成,帧大小是正确的,但事实并非如此.虚线边框的宽度超出了视图的宽度.顺便说一句,虚线看起来很棒!`self.frame.size`不正确. (3认同)
  • 很棒的代码!只有一个问题,当我将它应用于UIImageView时,它无法识别它的全宽,它大约占80%. (2认同)

xav*_*als 25

这是一个适用于任何项目的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以像这样从 Storyboard 进行编辑:

在此处输入图片说明

一对结果:

在此处输入图片说明

在此处输入图片说明

  • 这是最好的解决方案。适用于自动布局、自动调整视图大小,与其他答案不同,当视图高度增加时,这不会增加破折号高度(这是一件好事)。 (2认同)
  • 比其他解决方案更好。其他答案中的解决方案仅在视图的“高度”和“宽度”具有固定值的情况下才有效。但是有一个问题,视图上设置的值无法在情节提要中预览,有什么解决方案吗? (2认同)
  • 工作完美...线条和虚线准确,不超过视图的高度和宽度 (2认同)

小智 17

在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;
}
Run Code Online (Sandbox Code Playgroud)

重要的是要指出,如果将形状的位置定义为(0,0),边框的底角将放置在图像的中心,这就是我将其设置为:(frameSize.width/2,frameSize)的原因.height/2)

然后我使用我的方法使用我的UIImageView的UIImage获取虚线边框,并添加CAShapeLayer作为UIImageView层的子层:

[myImageView.layer addSublayer:[myImageView.image addDashedBorderWithColor:[[UIColor whiteColor] CGColor]]];
Run Code Online (Sandbox Code Playgroud)


Pra*_*d G 16

使用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);
Run Code Online (Sandbox Code Playgroud)

我认为这对你有所帮助.


sas*_*ash 14

斯威夫特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()
    }
}
Run Code Online (Sandbox Code Playgroud)

在故事板(作为自定义类)中使用或直接在代码中使用:

let v = UIViewWithDashedLineBorder(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

  • 令人惊讶的是,没有更多人对此表示赞同。与其他答案相比,该解决方案最适合自动布局。 (3认同)

btm*_*dan 10

为此,您需要为该特定对象添加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;
Run Code Online (Sandbox Code Playgroud)


Dan*_*ard 9

斯威夫特 4.2

基于 rmooney 的答案,作为UIView具有设置默认值的可配置参数的扩展。

请注意,如果视图具有,则这不起作用 self.translatesAutoresizingMaskIntoConstraints = false

extension UIView {
  func addDashedBorder(_ color: UIColor = UIColor.black, withWidth width: CGFloat = 2, cornerRadius: CGFloat = 5, dashPattern: [NSNumber] = [3,6]) {

    let shapeLayer = CAShapeLayer()

    shapeLayer.bounds = bounds
    shapeLayer.position = CGPoint(x: bounds.width/2, y: bounds.height/2)
    shapeLayer.fillColor = nil
    shapeLayer.strokeColor = color.cgColor
    shapeLayer.lineWidth = width
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round // Updated in swift 4.2
    shapeLayer.lineDashPattern = dashPattern
    shapeLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath

    self.layer.addSublayer(shapeLayer)
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 它可以与自动布局一起使用吗?因为它不适合我 (2认同)

Har*_*kar 7

对于斯威夫特 5

extension UIView {
    func addDashBorder() {
        let color = UIColor.white.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.name = "DashBorder"
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color
        shapeLayer.lineWidth = 1.5
        shapeLayer.lineJoin = .round
        shapeLayer.lineDashPattern = [2,4]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 10).cgPath

        self.layer.masksToBounds = false

        self.layer.addSublayer(shapeLayer)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何添加

vw.addDashBorder()
Run Code Online (Sandbox Code Playgroud)

如何再次去除边框

let _ = vw.layer.sublayers?.filter({$0.name == "DashBorder"}).map({$0.removeFromSuperlayer()})
Run Code Online (Sandbox Code Playgroud)


Rob*_*hen 6

Swift版本的QuartzCore答案.

import QuartzCore    

let dottedPattern = UIImage(named: "dottedPattern")
myView.layer.borderWidth = 1
myView.layer.borderColor = UIColor(patternImage: dottedPattern!).CGColor
Run Code Online (Sandbox Code Playgroud)

CAShapeLayer方法有效,但QuartzCore方法在处理Table View重新加载时更好,如果UIView它在单元格内部.

对于图像,你可以使用这样的东西(它真的很小):

在此输入图像描述

当我能逃脱时,我倾向于选择矢量而不是PNG:

  • 在Sketch中,创建一个4x4像素的矩形.
  • 共计四个
  • 将它们分成四角形,交替颜色
  • 将组导出为PDF
  • 在其中Images.xcassets,创建一个New Image Set名为dottedPattern的
  • 更改Scale FactorsSingle Vector
  • 放入您的PDF


c.l*_*dev 6

对于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);
Run Code Online (Sandbox Code Playgroud)


ddb*_*ddb 6

Swift 3中

let border = CAShapeLayer();
border.strokeColor = UIColor.black.cgColor;
border.fillColor = nil;
border.lineDashPattern = [4, 4];
border.path = UIBezierPath(rect: theView.bounds).cgPath
border.frame = theView.bounds;
theView.layer.addSublayer(border);
Run Code Online (Sandbox Code Playgroud)


sko*_*nos 5

• 斯威夫特 5

• 与自动布局配合使用

• 使用拐角半径

import UIKit

    class DashedBorderView: UIView {

    private let dashedLineColor = UIColor.black.cgColor
    private let dashedLinePattern: [NSNumber] = [6, 3]
    private let dashedLineWidth: CGFloat = 4

    private let borderLayer = CAShapeLayer()

    init() {
        super.init(frame: CGRect.zero)

        borderLayer.strokeColor = dashedLineColor
        borderLayer.lineDashPattern = dashedLinePattern
        borderLayer.backgroundColor = UIColor.clear.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.lineWidth = dashedLineWidth
        layer.addSublayer(borderLayer)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        borderLayer.frame = bounds
        borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: layer.cornerRadius).cgPath
    }
}
Run Code Online (Sandbox Code Playgroud)


Mil*_*a M 5

Swift 4,5 :- 添加DashedBorder

extension UIView {
    func setCellDeshBorder(color: UIColor = .appBlue?.withAlphaComponent(0.50) ?? UIColor()) {
        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.name = "DashBorder"
        shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = color.cgColor
        shapeLayer.lineWidth = 1.5
        shapeLayer.lineJoin = .round
        shapeLayer.lineDashPattern = [2,4]
        shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 10).cgPath
        self.layer.masksToBounds = false
        self.layer.addSublayer(shapeLayer)
    }
    
    func removeCellDeshBorder() {
        _ = self.layer.sublayers?.filter({$0.name == "DashBorder"}).map({$0.removeFromSuperlayer()})
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述