MehDi MehDi - 2 months ago 33
Android Question

canvas draw not smooth circles

At the first of my game, I draw some circles from alpha 0 to 255 using canvas(it's like making a fade_in animation by myself)

But if you see in picture(this picture captured in alpha 230),from alpha 0 to 254 these circles aren't smooth!(click on picture to see what I mean)

(and only when alpha become 255 the circles become smooth)
enter image description here
What's the problem and how can I fix this?

my code:
I have a game loop, that get canvas

canvas = gameView.getHolder().lockCanvas();


then in my view ,at first I set :

paintAlpha = 0;
paint = new Paint();
paint.setAntiAlias(true);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setAlpha(paintAlpha);
paint.setColor(Color.parseColor(color));


then in every loop(every ticks) I do this:

if(paintAlpha < 255) {
paintAlpha+=1;
paint.setAlpha(paintAlpha);
}
canvas.drawCircle(cx, cy, currentRadius, paint);


Solution:
Thanks to @nitesh.
The problem was because of surfaceView that can't set anti alias to canvas (in View you don't have this problem ,I don't know why)
By using Bitmap and draw on it and finally draw bitmap by canvas , the problem solved (instead of drawing on canvas directly)

Answer

Set the following property to paint object

paint.setAntiAlias(true);

For better understanding and other approaches refer this link https://medium.com/@ali.muzaffar/android-why-your-canvas-shapes-arent-smooth-aa2a3f450eb5#.p9iktozdi

From the article

Draw a bitmap first if:
- You need to persist the image.
- You need to draw transparent pixels.
- Your shapes don’t change often and/or require time consuming operations.
Use anti-aliasing to draw smooth edges.
Avoid redraws on the bitmap if possible or else, clear a bitmap before redrawing.

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (bitmap == null) {
        bitmap = Bitmap.createBitmap(200, 
                                     200, 
                                     Bitmap.Config.ARGB_8888);
        bitmapCanvas = new Canvas(bitmap);
    }
    bitmapCanvas.drawColor(
              Color.TRANSPARENT, 
              PorterDuff.Mode.CLEAR); //this line moved outside if
    drawOnCanvas(bitmapCanvas);
    canvas.drawBitmap(bitmap, mLeftX, mTopY, p);
}

protected void drawOnCanvas(Canvas canvas) {
    canvas.drawCircle(mLeftX + 100, mTopY + 100, 100, p);
}

enter image description here

Comments