I'm trying to programmatically draw into a UIImage like so:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIGraphicsBeginImageContextWithOptions(CGSizeMake(2, 2), YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
// These three lines of code apparently do nothing.
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextSetAllowsAntialiasing(context, false);
CGContextSetShouldAntialias(context, false);
CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:0 blue:0 alpha:1].CGColor);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
This code works except that the resulting image is very soft, obviously from an aggressive attempt at antialiasing/interpolation. I need the image to be scaled using nearest neighbour interpolation. How do I prevent this antialiasing?
Thank you!
While the image that you draw into the context doesn't use anti-aliasing (even though it doesn't actually make a difference for the particular image you're drawing), you still get the default interpolation behavior from the image view.
To change that, adjust the magnificationFilter
/minificationFilter
properties of the view's layer:
self.imageView.layer.magnificationFilter = kCAFilterNearest;
self.imageView.layer.minificationFilter = kCAFilterNearest;
(you need to add the QuartzCore framework for this to work.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With