Search code examples
androidviewdrawpixelgeometry

Android Draw Circle Pixel by Pixel


I am trying to draw a circle on my bitmap, pixel by pixel, using this code:

for(int j = ((int)x - 20); j < ((int)x + 20); j++){
    for(int k = ((int)y - 20); k < ((int)y + 20); k++){

        int colorX = bitmap.getPixel((int)j, (int)k);

        if(Color.red(colorX) == 0 && Color.green(colorX) == 0 && Color.blue(colorX) == 0){

            if(Math.sqrt(((j - (( int ) x )) ^ 2 ) + ((k - (( int ) y )) ^ 2) ) <= 20)
                bitmap.setPixel(j, k, Color.YELLOW);
        }
    }

}

But there is a problem, this is not drawing a circle.. it looks like a triangle..

Can someone help me?

Thanks alot in advance ;)


Solution

  • your mistake is a wrong use of ^ , its not a power operator

    regarding xfer modes i mentioned in the comment, see this custom view:

    class V extends View {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Xfermode mode = new AvoidXfermode(Color.BLACK, 0, AvoidXfermode.Mode.TARGET);
    
        public V(Context context) {
            super(context);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            int w = getWidth();
            float h = getHeight() / 3f;
            paint.setXfermode(null);
            paint.setColor(Color.RED);
            canvas.drawRect(0, 0, w, h, paint);
            paint.setColor(Color.BLACK);
            canvas.drawRect(0, h, w, 2*h, paint);
            paint.setColor(Color.GREEN);
            canvas.drawRect(0, 2*h, w, 3*h, paint);
    
            // draw the circle: it draws only in the middle black strip
            paint.setColor(Color.WHITE);
            paint.setXfermode(mode);
            canvas.drawCircle(w/2, 1.5f * h, h, paint);
        }
    }