2

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, please refer to below images:

Real Image: enter image description here

Required Image Output: enter image description here

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 get any way to crop this image diagonally since we can only pass parameters like Origin x,y & Size Height, Width.

halfer
  • 19,824
  • 17
  • 99
  • 186
Ajay Sharma
  • 4,509
  • 3
  • 32
  • 59

1 Answers1

3

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?

Felix Lamouroux
  • 7,414
  • 29
  • 46