Нарисуйте линию в UIView - PullRequest
81 голосов
/ 28 июня 2010

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

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

Ответы [ 8 ]

310 голосов
/ 22 марта 2011

Может быть, это немного поздно, но я хочу добавить, что есть лучший способ. Использовать 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);
}
120 голосов
/ 28 июня 2010

Самый простой способ в вашем случае (горизонтальная линия) - добавить подпредставление с черным цветом фона и рамкой [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 (вы можете увидеть мой пример кода для этого здесь ).

22 голосов
/ 07 февраля 2017

Свифт 3 и Свифт 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()
        }
    }
}
14 голосов
/ 19 февраля 2013

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

11 голосов
/ 27 ноября 2013

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

[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});
11 голосов
/ 24 мая 2013

Вы можете использовать класс UIBezierPath для этого:

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

Я подкласс 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];

}

Метод touchesBegin:

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

Метод touchesMoved:

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];

Метод touchesEnded:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];
0 голосов
/ 02 марта 2017

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

0 голосов
/ 02 марта 2017

Основано на ответе Гая Дахера.

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

Я бы сделал nil, проверил ли оператор if:

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()
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...