Search code examples
ios4core-graphicscalayerquartz-graphicsquartz-2d

Any way to disable CALayer's rasterizationScale interpolation / anti-aliasing in objective-c / iPhone / iOS SDK?


I want to get rid of any interpolation/antialiasing/etc when setting myLayer.rasterizationScale = 0.01 and myLayer.shouldRasterize = YES;

Example: enter image description here

Here's the code I'm trying:

- (void)drawRect:(CGRect)rect {
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CALayer *sourceLayer = self.delegate.sourceImageView.layer;
  sourceLayer.rasterizationScale = 0.01;
  sourceLayer.shouldRasterize = YES;
  [sourceLayer renderInContext:ctx];
  CGContextSetShouldAntialias(ctx, NO);
  CGContextSetAllowsAntialiasing(ctx, NO);
  CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
}

The expected result is that the image would display as a chunky/pixelated bitmap.

Any ideas? Thanks!

Edit: added full drawRect code, also tried moving the Antialias functions immediately following the UIGraphicsGetCurrentContext line.

Edit: Try #2 (fail!)

- (void)drawRect:(CGRect)rect
{
  CGContextRef ctx = UIGraphicsGetCurrentContext();
  CGContextSetShouldAntialias(ctx, NO);
  CGContextSetAllowsAntialiasing(ctx, NO);
  CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
  CALayer *layer = [CALayer layer];
  layer.contents = (id)[UIImage imageNamed:@"test.jpg"].CGImage;
  layer.frame = CGRectMake(0, 0, 320, 411);
  layer.rasterizationScale = 0.0001;
  layer.shouldRasterize = YES;
  layer.geometryFlipped = NO;
  layer.edgeAntialiasingMask = 0;
  layer.minificationFilter = kCAFilterNearest;
  [layer renderInContext:ctx];
}

Solution

  • For no interpolation, set the layer's magnificationFilter property to kCAFilterNearest. If desired, set the minificationFilter as well.

    In addition, you shouldn't set up the layer's properties inside the -drawRect: method. Instead, initialize the layer properties when initializing the view, or when you want to change the layer content.