UIView的用虚线(UIView with a Dashed line)

2019-06-17 20:06发布

是)我有的:

为了创建这条线,我基本上有一个UIView ,我做到以下几点:

void setLayerToLineFromAToB(CALayer *layer, CGPoint a, CGPoint b, CGFloat lineWidth)
{
    CGPoint center = { 0.5 * (a.x + b.x), 0.5 * (a.y + b.y) };
    CGFloat length = sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
    CGFloat angle = atan2(a.y - b.y, a.x - b.x);

    layer.position = center;
    layer.bounds = (CGRect) { {0, 0}, { length + lineWidth, lineWidth } };
    layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
}

注意:此代码在这里被发现的计算器,所以如果有人可以给我参考吧我将不胜感激。

我想要的是:

确定这样的“唯一”的东西我需要的是建立在这种模式UIView 。 我知道我能做到这一点使用Quartz2D(一个简单的方法来做到这一点,可以发现这里 )。 但我想通过操纵做CALayer ,而不是去到绘制方法。 为什么? 因为改造的,我对我做UIView ,我不能够正确绘制采用draw方法。

编辑1:

只是想说明我的问题:

你有什么通常是UIView ,然后你基本上只是绘制它的东西(在这种情况下,简单的线条)。 我发现摆脱“灰色”领域的解决方案,是不是画的东西,只是变换了UIView本身。 它工作得很好,如果你想要一个完全填充线,问题就来了,当你想要一个虚线之一。

Answer 1:

检查UIBezierPath setLineDash:count:phase: 方法 :

- (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase` method. 

这可以让你画虚线。

  1. 首先添加CAShapeLayer 。 其添加为子到你UIView 。 它有一个path属性。
  2. 现在做的一个目的UIBezierPath 。 用画线setLineDash

例如:

 UIBezierPath *path = [UIBezierPath bezierPath];
 //draw a line
 [path moveToPoint:yourStartPoint]; //add yourStartPoint here
 [path addLineToPoint:yourEndPoint];// add yourEndPoint here
 [path stroke];

 CGFloat dashPattern[] = {2.0f,6.0f,4.0f,2.0f}; //make your pattern here
 [path setLineDash:dashPattern count:4 phase:3];

 UIColor *fill = [UIColor blueColor];
 shapelayer.strokeStart = 0.0;
 shapelayer.strokeColor = fill.CGColor;
 shapelayer.lineWidth = 5.0;
 shapelayer.lineJoin = kCALineJoinMiter;
 shapelayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:10],[NSNumber numberWithInt:7], nil];
 shapelayer.lineDashPhase = 3.0f;
 shapelayer.path = path.CGPath;

注意:这个答案提供了一个提示,所以你可以相应地即兴您的要求(一个或多个)。



Answer 2:

:从王子的代码没有真正帮助我,所以我会给他+10的提示。 但最后,我加来与我自己的代码。 我也将添加一些上下文,所以它可以为未来的读者有用


最后的代码是这样的:

-(void)updateLine{

      // Important, otherwise we will be adding multiple sub layers
      if ([[[self layer] sublayers] objectAtIndex:0])
        {
            self.layer.sublayers = nil;
        }

        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
        [shapeLayer setBounds:self.bounds];
        [shapeLayer setPosition:self.center];
        [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
        [shapeLayer setLineWidth:3.0f];
        [shapeLayer setLineJoin:kCALineJoinRound];
        [shapeLayer setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
        [NSNumber numberWithInt:5],nil]];

        // Setup the path
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathMoveToPoint(path, NULL, beginPoint.center.x, beginPoint.center.y);
        CGPathAddLineToPoint(path, NULL, endPoint.center.x, endPoint.center.y);

        [shapeLayer setPath:path];
        CGPathRelease(path);

        [[self layer] addSublayer:shapeLayer];
}

在我的情况下,beginPoint和端点是由使用者可移动,使用国际志愿者组织。 所以,当他们中的一个动作:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqual:@"position"])
    {
        [self updateLine];
    }
}

我没有打太多的王子的代码。 我试图在draw:方法,它添加了虚线之间的细线(有点怪......),我也试过在initWithFrame: 。 就其本身而言他的代码,没有任何修改,会给我这种在控制台上的错误:

<Error>: CGContextSaveGState: invalid context 0x0
<Error>: CGContextSetLineWidth: invalid context 0x0
<Error>: CGContextSetLineJoin: invalid context 0x0
<Error>: CGContextSetLineCap: invalid context 0x0
<Error>: CGContextSetMiterLimit: invalid context 0x0
<Error>: CGContextSetFlatness: invalid context 0x0
<Error>: CGContextAddPath: invalid context 0x0
<Error>: CGContextDrawPath: invalid context 0x0
<Error>: CGContextRestoreGState: invalid context 0x0


Answer 3:

雨燕2.2

在这里下探此救别人的时间..

extension UIView {
    func addDashedLine(color: UIColor = UIColor.lightGrayColor()) {
        layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
        self.backgroundColor = UIColor.clearColor()
        let cgColor = color.CGColor

        let shapeLayer: CAShapeLayer = CAShapeLayer()
        let frameSize = self.frame.size
        let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

        shapeLayer.name = "DashedTopLine"
        shapeLayer.bounds = shapeRect
        shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height / 2)
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.strokeColor = cgColor
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = kCALineJoinRound
        shapeLayer.lineDashPattern = [4, 4]

        let path: CGMutablePathRef = CGPathCreateMutable()
        CGPathMoveToPoint(path, nil, 0, 0)
        CGPathAddLineToPoint(path, nil, self.frame.width, 0)
        shapeLayer.path = path

        self.layer.addSublayer(shapeLayer)
    }
}


Answer 4:

这是斯威夫特3版本亚历山大G“的答案的https://stackoverflow.com/a/38194152/1800489

extension UIView {

        func addDashedLine(color: UIColor = .lightGray) {
            layer.sublayers?.filter({ $0.name == "DashedTopLine" }).map({ $0.removeFromSuperlayer() })
            backgroundColor = .clear

            let shapeLayer = CAShapeLayer()
            shapeLayer.name = "DashedTopLine"
            shapeLayer.bounds = bounds
            shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = color.cgColor
            shapeLayer.lineWidth = 1
            shapeLayer.lineJoin = kCALineJoinRound
            shapeLayer.lineDashPattern = [4, 4]

            let path = CGMutablePath()
            path.move(to: CGPoint.zero)
            path.addLine(to: CGPoint(x: frame.width, y: 0))
            shapeLayer.path = path

            layer.addSublayer(shapeLayer)
        }
}


Answer 5:

虚线在Swift4•Xcode中9

木箱一个CAShapeLayer和使用lineDashPattern

extension UIView {

    func addDashedBorder() {
        //Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 2
        // passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment
        shapeLayer.lineDashPattern = [2,3]

        let path = CGMutablePath()
        path.addLines(between: [CGPoint(x: 0, y: 0),
                                CGPoint(x: self.frame.width, y: 0)])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)
    }
}

用法:

dashView.addDashedBorder()

输出:



Answer 6:

该接受的答案有一个协调的问题。 该生产线将在下面得出了一些距离。 我想不通为什么它有多大的距离增加了Y坐标。

有一种方法来绘制正确的坐标虚线:

-(void)drawRect:(CGRect)rect
{
     CGContextBeginPath(cx);
     CGContextRef cx = UIGraphicsGetCurrentContext();
     CGContextSetLineWidth(cx, _thickness);
     CGContextSetStrokeColorWithColor(cx, _color.CGColor);

     CGFloat dash[] = {_dashedLength,_dashedGap};
     CGContextSetLineDash(cx, 0, dash, 2); // nb "2" == ra count
//    CGContextSetLineCap(cx, kCGLineCapRound);

     CGContextMoveToPoint(cx, 0, _thickness);
     CGContextAddLineToPoint(cx, self.bounds.size.width, _thickness);
     CGContextStrokePath(cx);
     CGContextClosePath(cx);
}

这个答案是在2017年绘制散布(不虚!)线,以IBDesignable 。 不要不要不要忘记设置背景颜色为白色,当你想要一个黑色虚线! 默认情况下,该视图有一个黑色的背景色和线条颜色也是黑色的,所以我认为这是一个实线。 我花了半天才找到。 T_T



Answer 7:

首先要归功于RuiAAPeres和王子,我只是封装他们的回答到一个UIView对象,其他人可以拖放到他们的项目和使用

#import <UIKit/UIKit.h>

/**
 *  Simple UIView for a dotted line
 */
@interface H3DottedLine : UIView

/**
 *  Set the line's thickness
 */
@property (nonatomic, assign) CGFloat thickness;

/**
 *  Set the line's color
 */
@property (nonatomic, copy) UIColor *color;

/**
 *  Set the length of the dash
 */
@property (nonatomic, assign) CGFloat dashedLength;

/**
 *  Set the gap between dashes
 */
@property (nonatomic, assign) CGFloat dashedGap;

@end




@implementation H3DottedLine

#pragma mark - Object Lifecycle

- (instancetype)init {
    self = [super init];

    if (self) {
        // Set Default Values
        _thickness = 1.0f;
        _color = [UIColor whiteColor];
        _dashedGap = 1.0f;
        _dashedLength = 5.0f;
    }

    return self;
}

#pragma mark - View Lifecycle

- (void)layoutSubviews {
    // Note, this object draws a straight line. If you wanted the line at an angle you simply need to adjust the start and/or end point here.
    [self updateLineStartingAt:self.frame.origin andEndPoint:CGPointMake(self.frame.origin.x+self.frame.size.width, self.frame.origin.y)];
}

#pragma mark - Setters

- (void)setThickness:(CGFloat)thickness {
    _thickness = thickness;
    [self setNeedsLayout];
}

- (void)setColor:(UIColor *)color {
    _color = [color copy];
    [self setNeedsLayout];
}

- (void)setDashedGap:(CGFloat)dashedGap {
    _dashedGap = dashedGap;
    [self setNeedsLayout];
}

- (void)setDashedLength:(CGFloat)dashedLength {
    _dashedLength = dashedLength;
    [self setNeedsLayout];
}

#pragma mark - Draw Methods

-(void)updateLineStartingAt:(CGPoint)beginPoint andEndPoint:(CGPoint)endPoint {

    // Important, otherwise we will be adding multiple sub layers
    if ([[[self layer] sublayers] objectAtIndex:0]) {
        self.layer.sublayers = nil;
    }

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:self.center];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:self.color.CGColor];
    [shapeLayer setLineWidth:self.thickness];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:@[@(self.dashedLength), @(self.dashedGap)]];

    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, beginPoint.x, beginPoint.y);
    CGPathAddLineToPoint(path, NULL, endPoint.x, endPoint.y);

    [shapeLayer setPath:path];
    CGPathRelease(path);

    [[self layer] addSublayer:shapeLayer];
}

@end


文章来源: UIView with a Dashed line