【问题标题】:Draw partial image or clipping diagonally using Core Graphics使用 Core Graphics 绘制部分图像或对角线剪裁
【发布时间】:2020-05-17 17:55:25
【问题描述】:

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

实图:

所需的图像输出:

下面是使用颜色填充图层的代码:

    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 这样的参数。

【问题讨论】:

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


【解决方案1】:

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

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

这行得通吗?

【讨论】:

  • 让我看看这个......请
  • 为我工作得非常好:) 谢谢!
  • 什么是变量r?
  • 这是取自问题。我相信 r 和 rect 应该是一样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多