OGeek|极客世界-中国程序员成长平台

标题: iphone - 使用 Core Graphics 绘制部分图像或对角线剪裁 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:31
标题: iphone - 使用 Core Graphics 绘制部分图像或对角线剪裁

我希望使用 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 & Size Height, Width 这样的参数。



Best Answer-推荐答案


您应该能够将上下文剪辑到上下文的当前路径。您在剪辑上下文后所做的任何事情都将仅在该区域中可见:

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];

这行得通吗?

关于iphone - 使用 Core Graphics 绘制部分图像或对角线剪裁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850772/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4