Search code examples
objective-ciosuiimageviewuibezierpathimage-clipping

Create an irregular shaped frame


I've created a canvas within which I display an image that is clipped when it goes over the edges. I can do this fine with a square shaped frame, however the frame I want to use is the one below. Is there any way I can clip the image inside the frame without having to add a non transparent square border around the image, i.e. just using the black line that I've already drawn? (on iPad)

enter image description here


Solution

  • You'll need to use Core Graphics and Quartz to handle this sort of clipping/graphics manipulation. http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html#//apple_ref/doc/uid/TP30001066

    If you're using UIBezierPath, you may be able to achieve the clipping you're after using the following process http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_paths/dq_paths.html#//apple_ref/doc/uid/TP30001066-CH211-TPXREF101

    1. Convert your UIBezierPath to a CGPath
    2. Get your image into a CGContext
    3. Add your CGPath to the context via CGContextAddPath
    4. Clip your context using CGContextClip

    Alternatively, if you don't want to be messing with paths (and depending on whether this technique is suitable for your situation, your description of the issue makes it hard to tell), it might be worth using image masking to achieve the effect you're after. See the first link and look under "Bitmap Images and Image Masks".