使用Core Graphics绘制部分图像或对角剪裁

时间:2012-03-24 09:57:03

标签: iphone ios uiimage core-graphics ios-simulator

我希望使用Core Graphics绘制图像。但是我能够绘制部分图像,即水平和图像。垂直。但不是它,我希望以对角线方式使用它。有关更多说明,请参考下图:

真实图片: enter image description here

必需的图片输出: enter image description here

以下是用于填充图层颜色的代码:

    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    CGContextMoveToPoint(contextRef, r.origin.x, r.origin.y );
    CGContextAddLineToPoint(contextRef, r.origin.x , r.origin.y);
    CGContextAddLineToPoint(contextRef, r.origin.x + (r.size.width ), r.origin.y + (r.size.height));
    CGContextAddLineToPoint(contextRef, r.origin.x , r.origin.y + (r.size.height));
    CGContextAddLineToPoint(contextRef, r.origin.x  , r.origin.y);
    CGContextSetRGBFillColor(contextRef, [[color objectAtIndex:0]floatValue]/255.0f, [[color objectAtIndex:1]floatValue]/255.0f, [[color objectAtIndex:2]floatValue]/255.0f, .5);
    CGContextSetRGBStrokeColor(contextRef,[[color objectAtIndex:0]floatValue]/255.0f, [[color objectAtIndex:1]floatValue]/255.0f, [[color objectAtIndex:2]floatValue]/255.0f, 0.5);
    CGContextFillPath(contextRef);

现在,我想在这个图形图层上绘制一个图像,而不是在其中填充颜色。我没有任何方法裁剪此图像对角线,因为我们只能传递像Origin x,y& amp;尺寸高度,宽度。

提前致谢。

1 个答案:

答案 0 :(得分:3)

您应该能够将上下文剪辑到上下文的当前路径。剪切上下文后所做的任何操作只能在该区域中显示:

UIImage *img = ...;
CGContextRef contextRef = UIGraphicsGetCurrentContext();

CGContextMoveToPoint(contextRef, r.origin.x, r.origin.y );
CGContextAddLineToPoint(contextRef, r.origin.x , r.origin.y);
CGContextAddLineToPoint(contextRef, r.origin.x + (r.size.width ), r.origin.y + (r.size.height));
CGContextAddLineToPoint(contextRef, r.origin.x , r.origin.y + (r.size.height));
CGContextAddLineToPoint(contextRef, r.origin.x  , r.origin.y);

// clip context to current path
CGContextClip(contextRef);

// draw image
[img drawInRect:rect];

这有用吗?