drawInRect: losing Quality of Image resolution

2019-02-08 05:14发布

问题:

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.

回答1:

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);