Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird anti-aliasing in custom view

I have a custom UIView which is drawn using its -[drawRect:] method.

The problem is that the anti-aliasing acts very weird as black lines horizontal or vertical lines are drawn very blurry.

If I disable anti-aliasing with CGContextSetAllowsAntialiasing, everything is drawn as expected.

Anti-Aliasing:
alt text http://dustlab.com/stuff/antialias.png

No Anti-Aliasing (which looks like the expected result with AA):
alt text http://dustlab.com/stuff/no_antialias.png

The line width is exactly 1, and all coordinates are integral values.

The same happens if I draw a rectangle using CGContextStrokeRect, but not if I draw exactly the same CGRect with UIRectStroke.

like image 803
mrueg Avatar asked Sep 21 '09 13:09

mrueg


People also ask

How do you fix anti-aliasing?

Select Enhance the application setting in the NVIDIA Control Panel and then select a higher antialiasing level. Start the game and set antialiasing to "enable" or "on", or "2x" or "4x" through the game menu. Game does not support antialiasing when HDR rendering is enabled.

Should I turn anti-aliasing on or off?

Should I Turn Anti-Aliasing On or Off? If your visuals look great and you have a high-resolution display, you don't need to turn on anti-aliasing options. Anti-aliasing is for people who experience those unsightly “jaggies” and want to smooth out the edges of their graphics.

Which anti-aliasing mode should I use?

The best anti-aliasing method can be difficult to choose and it generally depends on your machine. If you have a top-notch, high-end computer then SSAA is the best solution. If your PC is mid-range at best, then you will probably have the most FPS with FXAA.

What are the types of anti-aliasing?

Aliasing is removed using four methods: Using high-resolution display, Post filtering (Supersampling), Pre-filtering (Area Sampling), Pixel phasing.


1 Answers

Since a stroke expands equal amounts to both sides, a line of one pixel width must not be placed on an integer coordinate, but at 0.5 pixels offset.

Calculate correct coordinates for stroked lines like this:

CGPoint pos = CGPointMake(floorf(pos.x) + 0.5f, floorf(pos.y) + 0.5f);

BTW: Don't cast your values to int and back to float to get rid of the decimal part. There's a function for this in C called floor.

like image 83
Nikolai Ruhe Avatar answered Nov 15 '22 10:11

Nikolai Ruhe