Clipping a CGGradient to a CGPath

和自甴很熟 提交于 2019-12-03 21:25:54
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height); // bottom left
CGPathAddLineToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);


for (int i=0; i<(points.count-1); i++) {
    //CGPoint pt1 = [[points objectAtIndex:i] CGPointValue];
    CGPoint pt2 = [[points objectAtIndex:i+1] CGPointValue];
    if (pt2.x > lastDrawnPt.x+2) {
        // only draw if we've moved sunstantially to the right

        //for the gradient
        CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);
        CGPathAddLineToPoint(thePath, NULL, pt2.x, pt2.y);


        lastDrawnPt = pt2;
    }
}

//finish the gradient clipping path
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, lastDrawnPt.y);
CGPathAddLineToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height); // bottom right
CGPathMoveToPoint(thePath, NULL, lastDrawnPt.x, self.bounds.size.height);
CGPathAddLineToPoint(thePath, NULL, firstDrawnPt.x, self.bounds.size.height); // bottom right

This just plots a series of line segments. For certain point values, it might look something like this:

| |||| |

It does not plot a single continuous shape. As such, this path is useless for clipping, as it is effectively empty; as you've seen, clipping to it will result in no further drawing being inside the clipping path.

Every lineto, curveto, arc, etc. works from the current point. You set that initially with moveto, but each lineto, curveto, arc, etc. does not clear the current point, it updates it. Thus, to create a single shape, you do one moveto followed by a succession of lineto (or curveto or arc), followed eventually by closepath.

Speaking of closepath

CGPathCloseSubpath(thePath);

This creates the only closed shape in the path, but since that shape has zero area (being only a line segment that doubles back on itself), it is still not helpful for clipping purposes.

I suspect that all you need to do is cut out at least one of the moveto segments (the one in the loop, if not also the one after it). Then, you can simplify the loop—use fast enumeration on the array, instead of using indexes, and cut out keeping track of the “last drawn point”.

Also, the correct type for indexes into an NSArray is NSUInteger, not int. Keep your types matched—it avoids pain later down the road.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!