Anti-alias diagonal edges of CALayer

tassock picture tassock · Jun 5, 2011 · Viewed 8.6k times · Source

When I set the transform property of my CALayer with a CATransform3DRotate, the layer is properly rotated. However, the edges of the layer are jagged and not anti-aliased. I've read a couple posts on the subject:

iPhone: CALayer + rotate in 3D + antialias?

iPhone - Jagged Edges when applying perspective to CALayer

I've tried to incorporate their advice by setting the following properties on my diagonal layer

CALayer* layer = myView.layer;
layer.shadowOpacity = 0.01;
layer.edgeAntialiasingMask = kCALayerTopEdge | kCALayerBottomEdge | kCALayerRightEdge | kCALayerLeftEdge;
layer.borderWidth = 1.0;
layer.borderColor = [UIColor clearColor].CGColor;
layer.backgroundColor = [UIColor greenColor].CGColor;

I've also overridden the drawLayer:inContext: method of my diagonal layer to ensure anti-aliasing:

-(void)drawLayer:(CALayer*)layer inContext:(CGContextRef)context
{
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
    CGContextFillRect(context, self.bounds);
}

What am I missing?

Answer

Daniel Rinser picture Daniel Rinser · Oct 18, 2013

As of iOS7, this is now finally possible on a per-layer basis and without any ugly hacks like transparent pixels or workarounds like rasterization:

layer.allowsEdgeAntialiasing = YES;

Interestingly, this is not covered by the official CALayer documentation, but is definitely a public API. See the iOS7 API diffs and Peter Steinberger's great write-up on Hidden Gems and Workarounds in iOS7.