19

I am trying to erase image using following code

 CGColorRef strokeColor = [UIColor whiteColor].CGColor;

 UIGraphicsBeginImageContext(imgForeground.frame.size);

 CGContextRef context = UIGraphicsGetCurrentContext();
 [imgForeground.image drawInRect:CGRectMake(0, 0, imgForeground.frame.size.width, imgForeground.frame.size.height)];

 CGContextSetLineCap(context, kCGLineCapRound);
 CGContextSetLineWidth(context, 10);

 CGContextSetStrokeColorWithColor(context, strokeColor);
 CGContextSetBlendMode(context, kCGBlendModeClear);

 CGContextBeginPath(context);
 CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
 CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
 CGContextStrokePath(context);

 imgForeground.image  = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();

But I just find out Image losing its resolution due to drawInRect.

Before After

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shashank Kulshrestha
  • 1,556
  • 17
  • 31

1 Answers1

48

You should go with UIGraphicsBeginImageContextWithOptions instead of UIGraphicsBeginImageContext, so that a scale factor can be specified.

For example, this will use the scale factor of the device's main screen:

UIGraphicsBeginImageContextWithOptions(imgForeground.frame.size, NO, 0);
Nenad M
  • 3,055
  • 20
  • 26
  • What if image is not of size of Window? Than what to replace with imgForeground.window.screen.scale – Shashank Kulshrestha Feb 06 '13 at 12:43
  • Hi! Well, the 3rd parameter is the scale and not any dimension (i.e. size)! For all iPhones, iPodTouches etc. that do NOT have Retina Displays it will return a 1.0f, while Retina Display devices will give a 2.0f. – Nenad M Feb 06 '13 at 12:54
  • 1
    replace 'imgForeground.window.screen.scale' with '[[UIScreen mainScreen] scale]', so it becomes more clear that the scale of the "screen" is meant! – Nenad M Feb 06 '13 at 13:16
  • 3
    Third param can be simply `0`, it means that scale will be choosen automatically (usual convention in Cocoa) – Nik Oct 04 '13 at 13:40