Подтвердить что ты не робот

Рисование линии в UIView

Мне нужно нарисовать горизонтальную линию в UIView. Самый простой способ сделать это. Например, я хочу нарисовать черную горизонтальную линию на y-coord = 200.

Я НЕ использую Interface Builder.

4b9b3361

Ответ 1

Самый простой способ в вашем случае (горизонтальная линия) - добавить подвью с черным цветом фона и рамкой [0, 200, 320, 1].

Пример кода (надеюсь, ошибок нет - я написал его без Xcode):

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];
[lineView release];
// You might also keep a reference to this view 
// if you are about to change its coordinates.
// Just create a member and a property for this...

Другой способ - создать класс, который будет рисовать линию в методе drawRect (вы можете увидеть мой пример кода для здесь).

Ответ 2

Возможно, это немного поздно, но я хочу добавить, что есть лучший способ. Использование UIView является простым, но относительно медленным. Этот метод переопределяет то, как изображение рисует себя и работает быстрее:

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

Ответ 3

Просто добавьте ярлык без текста и с цветом фона. Установите координаты по вашему выбору, а также высоту и ширину. Вы можете сделать это вручную или с помощью Interface Builder.

Ответ 4

Для этого можно использовать класс UIBezierPath:

И вы можете рисовать столько строк, сколько хотите:

У меня есть subclassed UIView:

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

И инициализировал объекты pathArray и dictPAth, которые будут использоваться для рисования линии. Я пишу основную часть кода из своего собственного проекта:

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

touchhesBegin метод:

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

касается методаMoved:

UITouch *touch = [touches anyObject];
endPoint = [touch locationInView:self];

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

касается метода:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];

Ответ 5

Еще одна (и еще более короткая) возможность. Если вы находитесь внутри drawRect, выполните следующие действия:

[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});

Ответ 6

Swift 3 и Swift 4

Вот как вы можете нарисовать серая линия в конце вашего представления (та же идея, что и b123400)

class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

Ответ 7

На основании ответа Ги Дэера.

Я стараюсь избегать использования? потому что это может привести к сбою приложения, если GetCurrentContext() возвращает nil.

Я бы сделал nil проверить, если инструкция:

class CustomView: UIView 
{    
    override func draw(_ rect: CGRect) 
    {
        super.draw(rect)
        if let context = UIGraphicsGetCurrentContext()
        {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

Ответ 8

Добавьте метку без текста и с цветом фона, соответствующим размеру кадра (например: height = 1). Сделайте это через код или в построителе интерфейса.