Draw Border around UIImage

Discussion in 'iOS Programming' started by newtoiphonesdk, Apr 16, 2013.

  1. newtoiphonesdk macrumors 6502a

    Jul 30, 2010
    am needing a border around a UIImage. The UIImage is added to a PDF file. Here is the code for drawing the image currently.

    - (void) drawImage2
        UIImage * demoImage = self.imageCopy;
        NSData *jpegData = UIImageJPEGRepresentation(demoImage, 0.80);
        CGDataProviderRef dp = CGDataProviderCreateWithCFData(( CFDataRef)jpegData);
        CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dp, NULL, true, kCGRenderingIntentDefault);
        [[UIImage imageWithCGImage:cgImage] drawInRect:CGRectMake(513, 314, 135, 135)];  
    Any suggestions for how I can do this? I know how to do it using CALayers with a UIImageView, but not sure here since I don't have the view.
  2. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia

    Use Core Image drawing calls. Something like this:

    	CGContextRef a_ctx = UIGraphicsGetCurrentContext();
    	CGRect boxBounds;
    	boxBounds = CGRectMake(513, 314, 135, 135); //Or whatever your outline needs to be.
    	CGContextSetStrokeColorWithColor(a_ctx, [outlineColor CGColor]);
    	CGContextSetLineWidth( a_ctx, 1.0);
    	CGMutablePathRef a_path = CGPathCreateMutable();
    	CGPathAddRect(a_path, NULL, boxBounds);
    	CGContextAddPath(a_ctx, a_path);
    By the way, your code above seems kind of silly. You start out with a UIIMage. You convert it to JPEG data. You use that JPEG data to create a CGImage. You use THAT to create a UIImage, and you draw THAT in the current context. Why not skip all that and use the single line

       [self.imageCopy drawInRect:CGRectMake(513, 314, 135, 135)];  
    And finally, in your code above you are leaking the cgImage that you create. Since it has the word create in it's name it follows the Core Foundation create rule, and you need to release it when you're done with it. If you keep your code, you need to add

    after the call to imageWithCGImage

Share This Page