Draw a border around the contents of a UIImageView

I have a UIImageView with an image with a car with a transparent background:

enter image description here

And I want to draw a frame around the car:

enter image description here

How can I achieve this effect?

At the moment, I have tested CoreGraphics in this way, but without good results:

    // load the image
    UIImage *img = carImage;

    UIGraphicsBeginImageContext(img.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [[UIColor redColor] setFill];
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, img.size.width * 1.1, img.size.height*1.1);
    CGContextDrawImage(context, rect, img.CGImage);

    CGContextClipToMask(context, rect, img.CGImage);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

Any help? Thank.

+4
source share
1 answer

Here is what I did:

I did this in Swift to test it on playgrounds , think that you can easily translate it to Objective-C :

import UIKit


func drawOutlie(#image:UIImage, color:UIColor) -> UIImage
{
  var newImageKoef:CGFloat = 1.08

  var outlinedImageRect = CGRect(x: 0.0, y: 0.0, width: image.size.width * newImageKoef, height: image.size.height * newImageKoef)

  var imageRect = CGRect(x: image.size.width * (newImageKoef - 1) * 0.5, y: image.size.height * (newImageKoef - 1) * 0.5, width: image.size.width, height: image.size.height)

  UIGraphicsBeginImageContextWithOptions(outlinedImageRect.size, false, newImageKoef)

  image.drawInRect(outlinedImageRect)

  var context = UIGraphicsGetCurrentContext()
  CGContextSetBlendMode(context, kCGBlendModeSourceIn)

  CGContextSetFillColorWithColor(context, color.CGColor)
  CGContextFillRect(context, outlinedImageRect)
  image.drawInRect(imageRect)

  var newImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  return newImage

}

var imageIn = UIImage(named: "158jM")

var imageOut = drawOutlie(image: imageIn, UIColor.redColor())

So how does it work?

  • (aka canvas) , ( )

, : var newImageKoef:CGFloat = 1.08

,

enter image description here

+7

All Articles