web-dev-qa-db-fra.com

Tracez une ligne dans UIView

Je dois dessiner une ligne horizontale dans UIView. Quelle est la façon la plus simple de le faire? Par exemple, je veux tracer une ligne horizontale noire à y-coord = 200.

Je n'utilise pas Interface Builder.

83
John Smith

Le moyen le plus simple dans votre cas (ligne horizontale) est d’ajouter une sous-vue avec une couleur de fond et un cadre noirs [0, 200, 320, 1].

Échantillon de code (j'espère qu'il n'y a pas d'erreur - je l'ai écrit sans 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...

Une autre méthode consiste à créer une classe qui tracera une ligne dans sa méthode drawRect (vous pouvez voir mon exemple de code pour cela ici ).

120
Michael Kessler

Peut-être que c'est un peu tard, mais je veux ajouter qu'il y a une meilleure façon. Utiliser UIView est simple, mais relativement lent. Cette méthode remplace la façon dont la vue se dessine et est plus rapide:

- (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);
}
310
b123400

Swift 3 et Swift 4

Voici comment tracer une ligne grise à la fin de votre affichage (même idée que la réponse de 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()
        }
    }
}
24
Guy Daher

Ajoutez simplement une étiquette sans texte et avec une couleur d'arrière-plan. Définissez les coordonnées de votre choix ainsi que la hauteur et la largeur. Vous pouvez le faire manuellement ou avec Interface Builder.

14
Phanindra

Une autre possibilité (et une possibilité encore plus courte). Si vous êtes dans drawRect, utilisez l'une des options suivantes:

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

Vous pouvez utiliser UIBezierPath Class pour cela:

Et pouvez dessiner autant de lignes que vous le souhaitez:

J'ai sous-classé UIView:

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

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

Et initialisé les objets pathArray et dictPAth qui seront utilisés pour le dessin au trait. J'écris la partie principale du code de mon propre projet:

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

}

méthode toucheBegin:

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

toucheMoved Méthode:

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

toucheEnded Méthode:

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

Basé sur la réponse de Guy Daher.

J'essaie d'éviter d'utiliser? car cela peut provoquer un blocage de l'application si GetCurrentContext () renvoie nil.

Je ferais rien vérifier si déclaration:

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()
        }
    }
}
0
Robert Harrold