如何使用随机颜色创建网格并将其与线条连接

时间:2017-03-15 06:43:54

标签: ios objective-c uibezierpath

我知道如何创建网格,但线条无法在网格中正确绘制。 我尝试过,但我没有找到任何好的解决方案。任何人都可以帮我完成这件事。 (请参阅附图)

这是我的代码

-(void) drawRect:(CGRect)rect
{

    int xStart = 10, yStart = 5;
    int gridSize = 300;

    UIBezierPath *topPath = [UIBezierPath bezierPath];

    int x = xStart + 0 * gridSize / 5;

    [topPath moveToPoint:CGPointMake(x, yStart)];
    [topPath addLineToPoint:CGPointMake(x, yStart+gridSize)];

    int y = yStart + 0 * gridSize / 5;
    [topPath moveToPoint:CGPointMake(xStart, y)];
    [topPath addLineToPoint:CGPointMake(xStart+gridSize, y)];

    // draw vertical lines
    for(int xId=1; xId<=5; xId++) {
        int x = xStart + xId * gridSize / 5;
        [topPath moveToPoint:CGPointMake(x, yStart)];
        [topPath addLineToPoint:CGPointMake(x, yStart+gridSize)];
    }
    // draw horizontal lines
    for(int yId=1; yId<=5; yId++) {

        int y = yStart + yId * gridSize / 5;
        [topPath moveToPoint:CGPointMake(xStart, y)];
        [topPath addLineToPoint:CGPointMake(xStart+gridSize, y)];
    }
    [[UIColor yellowColor] setStroke];
    [topPath stroke];



    [incrementalImage drawInRect:rect];
    [path stroke];

    if (touchStart.x != -1)
    {
        // calculate the line rotation
        enum { horizontal, vertical } lineRot = horizontal;

        if (touchStart.y == touchCurrent.y)
        {
            //   straight line
            lineRot = horizontal;
        }
        else
        {
            //calculate the slope
            double slope = fabs((touchCurrent.y - touchStart.y) / (touchCurrent.x - touchStart.x));

            if (slope > 1)
                lineRot = vertical;
        }

        // draw the actual line
        CGPoint lineEndPoint = { };
        //
        if (lineRot == horizontal)
            lineEndPoint = (CGPoint) { touchCurrent.x, touchStart.y}; // horizontal line
        else
            lineEndPoint = (CGPoint) { touchStart.x, touchCurrent.y }; // vertical line
        //
        // actually draw the line
        [[UIColor yellowColor] setStroke];


        path = [UIBezierPath bezierPath];
        [path moveToPoint:touchStart];
        [path addLineToPoint:lineEndPoint];
        [path setLineWidth:10.0];
        [path stroke];
    }

}

Please see the image attached

0 个答案:

没有答案