Draw partial image or clipping diagonally using Core Graphics

寵の児 提交于 2019-12-12 09:11:52

问题


I am looking to draw an image using Core Graphics.However I am able to draw the partial image i.e Horizontally & vertically. But instead of it I want to have it in a Diagonal Way.For more clarification, pls refer to below image :

Real Image :

Required Image Output:

Below is the code using to fill the Layer with Color :

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

Now, I want to Draw an image on this Graphics Layer rather than filling color in it.I didn't got any way to crop this image Diagonally since we can only pass parameters like Origin x,y & Size Height, Width.

Thanks in advance.


回答1:


You should be able to clip the context to the context's current path. Anything you do after having clipped the context will be visible only in that area:

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

Did this work?



来源:https://stackoverflow.com/questions/9850772/draw-partial-image-or-clipping-diagonally-using-core-graphics

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