IOS使用drawrect在图像上创建蒙版

时间:2014-09-08 02:48:49

标签: ios objective-c ios7 ios6

我创建了一个绘制折线图的函数,如何使用折线图作为蒙版并将其放在图像上?图像在不同的高度上有不同的颜色,所以我想做的是用线图屏蔽后,线图将在不同的层次上显示不同的颜色。非常感谢帮助我:))

- (void)drawLineGraphWithContext:(CGContextRef)ctx
{
    CGContextSetLineWidth(ctx, 2.0);
    CGContextSetStrokeColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);

    int maxGraphHeight = kGraphHeight - kOffsetY;

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, kOffsetX, kGraphHeight - maxGraphHeight * data[0]);

    for (int i = 1; i < sizeof(data); i++)
    {
        CGContextAddLineToPoint(ctx, kOffsetX + i * kStepX, kGraphHeight - maxGraphHeight * data[i]);
    }

    CGContextDrawPath(ctx, kCGPathStroke);

    CGContextSetFillColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);

    for (int i = 0; i < sizeof(data) - 1; i++)
    {
        float x = kOffsetX + i * kStepX;
        float y = kGraphHeight - maxGraphHeight * data[i];
        CGRect rect = CGRectMake(x - kCircleRadius, y - kCircleRadius, 2 * kCircleRadius, 2 * kCircleRadius);
        CGContextAddEllipseInRect(ctx, rect);
    }
    CGContextDrawPath(ctx, kCGPathFillStroke);


CGPathRef myPath = CGContextCopyPath(ctx);

CAShapeLayer *shapeLayer =  [[CAShapeLayer alloc] init];
CGPathRef myPath = CGContextCopyPath(ctx);

shapeLayer.path = myPath;


_imageView.layer.mask = shapeLayer;



}

1 个答案:

答案 0 :(得分:0)

尝试这样做。

 1. Put the Image into an ImageView.
 2. Since you already have the Path. And rite now, you will get the last
    point as `path.currentPoint`. Add a Line to the `bottomRight` then
    to `bottomLeft` and then to the `startingPoint` of the Path. You
    will need to store the FirstPoint of the Path Somewhere for this.
    Also, all the Path drawing should be in reference to the `bounds` of
    the ImageView.
 3. Create a CAShapeLayer with the path above. `shapeLayer.path = path`.
 4. Set it as mask of the imageView -- imageView.mask = shapeLayer`.

以这种方式试试。干杯,玩得开心。