Home » Android » android – Why Paint.ANTI_ALIAS_FLAG does not seem to work when drawing at same place on Canvas?

android – Why Paint.ANTI_ALIAS_FLAG does not seem to work when drawing at same place on Canvas?

Posted by: admin June 15, 2020 Leave a comment

Questions:

There is an issue with anti-alias when trying to draw multiple times at same place using the android Canvas.

First I’m initializing paint = new Paint(Paint.ANTI_ALIAS_FLAG) and then setting stroke cap to Paint.Cap.ROUND.

Then, if I call canvas.drawPoint(x, y, paint) once causes the following result:

enter image description here

While calling canvas.drawPoint(x, y, paint) multiple times (100 in this example) causes this:

enter image description here

I’ve created an example with minimal code to run this on GitHub: android-canvas-antialias

I noticed if I draw the points with a certain distance, the anti-alias seems to work as expected (first image). But drawing it with little offset causes the same anti-alias issue (second image).

Is there any setup that need to be done for this to work while drawing the points at same place? Or I simply may not be drawing at same place (or with very little offset)?

EDIT: the real issue is because I’m trying to draw a width variable line segment. See the MainActivity.drawSegment on git repository.

How to&Answers:

I don’t think this is a problem, I mean, a bug itself. And even if solvable trivially I guess.

The pixels of the edge of the circle are draw with some alpha, e.g. a red pixel with 25% alpha if you overlay it with more 3 pixels with same alpha you will get a 100% red pixel.

A workaround would be manage all shapes created and check if some of them has the same size + position (maybe color too) and just draw one of them.

The link below explain how the Antialiasing works, might help.

http://web.cs.wpi.edu/~matt/courses/cs563/talks/antialiasing/methods.html

Answer:

It works correctly. Anti-aliasing is when the edges of the shape are semi-transparent. When you multiply the shapes, the semi-transparent pixels become not transparent and you get “ragged” edges.

The solution is not to do this.