2016-05-16 6 views
4

У меня есть диаграмма, которая имеет форму датчика, который имеет несколько элементов дизайна (см. Вложение). Ключевые части, с которыми я борюсь, действительно получают приличную дугу с пунктирными линиями.UIView чертеж диаграммы типа дуги

До сих пор я не уверен, должен ли я идти по трассе Core Graphics или использовать что-то в UIKit, то есть UIBezierPath.

Я попытался это в классе, которые проходят UIView, который дает мне пунктирные линии, но сама дуга не достаточно хорошо:

class Example: UIView { 

    override func drawRect(rect: CGRect) { 

     let context = UIGraphicsGetCurrentContext() 
     CGContextSetLineWidth(context, 10.0) 
     CGContextSetStrokeColorWithColor(context, UIColor.greenColor().CGColor) 
     let dashArray:[CGFloat] = [1,10, 0, 0] 
     CGContextSetLineDash(context, 2, dashArray, 4) 
     CGContextMoveToPoint(context, 10, 200) 
     CGContextAddQuadCurveToPoint(context, 0, 0, 100, 200) 
     CGContextStrokePath(context) 
    } 
} 

Есть то некоторые другие способы, чтобы получить это происходит с помощью UIBezierPath, но я не уверен, как бы я применил пунктирные линии здесь ...

Основная цель получения дуги с пунктирными линиями - моя главная цель atm - я уверен, как только я получу это будет возможность тренировки градиента и анимации :)

Любая помощь будет оценена :)

enter image description here

ответ

3

Что вам нужно, это два пути Безье с различными пунктирными ширины.

Вы можете начать отсюда:

T0 получить более высокий приборный Безье:

enter image description here

UIBezierPath* oval2Path = [UIBezierPath bezierPathWithOvalInRect: yourRect]; 
[UIColor.redColor setStroke]; 
oval2Path.lineWidth = 13; 
CGFloat oval2Pattern[] = {2, 20}; 
[oval2Path setLineDash: oval2Pattern count: 2 phase: 0]; 
[oval2Path stroke]; 

и получить небольшой тир по образцу Безье, необходимо сократить разрыв между штрихами:

enter image description here

UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: yourRect]; 
[UIColor.redColor setStroke]; 
ovalPath.lineWidth = 6; 
CGFloat ovalPattern[] = {2, 1}; 
[ovalPath setLineDash: ovalPattern count: 2 phase: 0]; 
[ovalPath stroke]; 

и теперь вы можете поместить эти два Безье путь вместе:

enter image description here

- (void)drawFrame: (CGRect)frame 
{ 

    // Oval Drawing 
    UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame), CGRectGetMinY(frame), 70, 70)]; 
    [UIColor.redColor setStroke]; 
    ovalPath.lineWidth = 6; 
    CGFloat ovalPattern[] = {2, 1}; 
    [ovalPath setLineDash: ovalPattern count: 2 phase: 0]; 
    [ovalPath stroke]; 


    // Oval 2 Drawing 
    UIBezierPath* oval2Path = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + 0.5, CGRectGetMinY(frame) - 0.5, 70, 70)]; 
    [UIColor.redColor setStroke]; 
    oval2Path.lineWidth = 13; 
    CGFloat oval2Pattern[] = {2, 20}; 
    [oval2Path setLineDash: oval2Pattern count: 2 phase: 0]; 
    [oval2Path stroke]; 
} 

Swift:

func drawCanvas1(frame frame: CGRect = CGRect(x: 86, y: 26, width: 70, height: 70)) { 
    let context = UIGraphicsGetCurrentContext() 

    // Oval Drawing 
    let ovalPath = UIBezierPath(ovalInRect: CGRect(x: frame.minX, y: frame.minY, width: 70, height: 70)) 
    UIColor.redColor().setStroke() 
    ovalPath.lineWidth = 6 
    CGContextSaveGState(context) 
    CGContextSetLineDash(context, 4.5, [0, 1], 2) 
    ovalPath.stroke() 
    CGContextRestoreGState(context) 


    // Oval 2 Drawing 
    let oval2Path = UIBezierPath(ovalInRect: CGRect(x: frame.minX + 0.5, y: frame.minY - 0.5, width: 70, height: 70)) 
    UIColor.redColor().setStroke() 
    oval2Path.lineWidth = 13 
    CGContextSaveGState(context) 
    CGContextSetLineDash(context, 39, [1, 10], 2) 
    oval2Path.stroke() 
    CGContextRestoreGState(context) 
} 

Аналогично вы можете следовать такой же подход к дугам, где нужно просто заменить метод bezierPathWithOval на метод bezierPathWithArcCenter

Пожалуйста, обратите внимание, что:

CGFloat ovalPattern[] = {2, 1}; // 2 широтно черточки и 1 является разрыв между штрихами

Вы можете отрегулировать эти значения для точности!

+0

Это на самом деле довольно умно. Я не знаю, что я подумал бы об этом. –

+0

Вы можете сделать так много комбинаций на дорожках безье, используя инструмент рисования красок! вы shold дать ему попробовать @ GlennHowes –

+0

Wow спасибо @TejaNandamuri - давая вам голосование за усилия в одиночку! Будет ли проверять mo, если это работает :) – sukh

0

В настоящее время это лучшее, что я мог бы сделать, чтобы перевести это на UIBezierPath. Поскольку я нахожу лучшие способы сделать это, я обновлю свой код.

// First Arc // 
guageArcOne.path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true).CGPath 
guageArcOne.fillColor = UIColor.clearColor().CGColor 
guageArcOne.strokeColor = UIColor.greenColor().CGColor 
guageArcOne.lineWidth = 10.0 
guageArcOne.strokeEnd = 1.0 
guageArcOne.lineDashPattern = [1,10, 0, 0] 
guageArcOne.lineDashPhase = 2.0 
arcContainerView.layer.addSublayer(guageArcOne) 

// Second Arc // 
guageArcTwo.path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true).CGPath 
guageArcTwo.fillColor = UIColor.clearColor().CGColor 
guageArcTwo.strokeColor = UIColor.greenColor().CGColor 
guageArcTwo.lineWidth = 10.0 
guageArcTwo.strokeEnd = 1.0 
guageArcTwo.lineDashPattern = [1,2, 0, 0] 
guageArcTwo.lineDashPhase = 2.0 
arcContainerView.layer.addSublayer(guageArcTwo) 

EDIT: Добавлена ​​вторая дуга для более коротких, более частых штрихов.