How to Draw a line pixel by pixel using objective

2019-06-11 02:46发布

I want to draw a line(on iphone) such that i can view each pixel being draw.

I am currently calling the drawRect method using a timer.

Following is the code where i am drawing a wave using the values from an array:

static int i=0;
int x = 10;
int y = 0;
int x2;
int y2;

- (void)drawRect:(CGRect)rect 
{
// Drawing code.
CGContextRef c = UIGraphicsGetCurrentContext();

CGFloat black[4] = {0.0f,0.0f,0.0f,1.0f};
CGContextSetStrokeColor(c, black);
CGContextBeginPath(c);
NSLog(@"fired...");
int ecg[358] = {36, 37, 37, 36, 34, 33, 33, .... ,36}; //Assume the data is there

CGContextMoveToPoint(c, x, y);

x2 = i;
y2 = ecg[i];
CGContextAddLineToPoint(c, x2, y2);
x = x2;
y = y2;

CGContextStrokePath(c); 
[self setNeedsDisplay];
i++;
}

- (void) awakeFromNib
{
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(drawRect:) userInfo:nil repeats:YES];
}

I can only see one line at a time being draw when drawRect is called. But i dont see the entire image. I cannot think of a different approach in order to see the wave being draw on the screen.

Also the method initWithFrame is never called so had to go with awakeFromNib to declare the timer, correct me if i am wrong.

Any pointers to animate the drawing of a line would help.

Thank you

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-11 03:06

Just re-draw the stuff up to the point that you want, like:

    for (int j = 0; j <= i; j++) {
        x2 = j;
        y2 = ecg[j];
        CGContextAddLineToPoint(c, x2, y2);
        x = x2;
        y = y2;
    }

    CGContextStrokePath(c); 

Do not call setNeedsDisplay: in your drawRect:, it causes the view to be redrawn immediately afterwards over and over again. Also, try to avoid global variables. For examples, there's no need to "cache" x, x2, y and y2 here. Define them inside drawRect:.

查看更多
登录 后发表回答