-1

I'm using drawRect to create a line. Based on the "4inch screen" my line is the correct place. When ran on a "3.5 inch screen" the line is lower down and in the wrong place.

- (void)drawRect:(CGRect)rect
{
    CGContextRef firstLine = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(firstLine, 15, 389);
    CGContextAddLineToPoint(firstLine, 320, 389);
    CGContextStrokePath(firstLine);
    CGContextSetLineWidth(firstLine, 1.1);
}

I know I need to do something with self.frame.heigh to make it dynamic to screen size but don't know where to put it.

Tulon
  • 4,011
  • 6
  • 36
  • 56
user2920762
  • 223
  • 1
  • 8
  • 17
  • Your code is already not working: `CGContextStrokePath(firstLine); CGContextSetLineWidth(firstLine, 1.1);` You cannot set the line width _after_ you have drawn. Also it is pointless to set line width to a funny fractional amount like that, since there are no fractional pixels on the screen. – matt May 11 '14 at 16:28

1 Answers1

1

Get the height of the view bounds each time you draw it and you are good to go.

- (void)drawRect:(CGRect)rect
{
   /* Get the height of the view */
    float height = CGRectGetHeight(self.bounds);
  /* the amount to inset the line by */
    float lineInset = 20;
 /* y-position after insetting the line */
    float yPosition = height - lineInset;
    CGContextRef firstLine = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(firstLine, 15, yPosition);
    CGContextAddLineToPoint(firstLine, 320, yPosition);
    CGContextSetLineWidth(firstLine, 1.1);
    CGContextStrokePath(firstLine);
}
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • Very insightful and helpful answer! - You have accidentally created a float `lineInset` that you never use; you should fix that. Note also my comment to his question: do not repeat his mistake of calling `CGContextSetLineWidth` after drawing where it has no effect. – matt May 11 '14 at 16:32
  • Oh, one more thing - you should also explain the OP _why_ your answer works where his code doesn't. (It's because the height of the view whose `drawRect` this is differs on 4-inch vs. 3.5-inch screen.) – matt May 11 '14 at 16:33
  • @matt Thank you very much. I didn't notice that I was not using the lineInset variable and that he was setting the linewidth after drawing it. I corrected it. – Sandeep May 11 '14 at 16:35