Search code examples
androidandroid-canvas

Android: How to detect if a point in the line drawn by canvas?


The line is drawn with a color which is different from the background color. Then put the bitmap in canvas in an array. If the color of the given point in the array is the same as line's color, then the point is in the line. In addition, I do not want to display the canvas in my app.

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btnCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCheck = (Button) findViewById(R.id.btn_check);
        btnCheck.setOnClickListener(click);
    }

    private View.OnClickListener click = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int width = 60, height =60;
            int startX = 15, startY = 8;
            int stopX  = 15, stopY  = 20;

            Paint paint = new Paint();
            paint.setStrokeWidth(5);
            paint.setColor(Color.RED);

            Bitmap baseBitmap;
            Canvas canvas;

            baseBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            canvas = new Canvas(baseBitmap);
            canvas.drawColor(Color.WHITE);

            canvas.drawLine(startX, startY, stopX, stopY, paint);

            int[] arrImage = new int[width*height];
            baseBitmap.setPixels(arrImage, 0, width, 0, 0, width, height);

            int[][] points = new int[][]{
                    {15, 8},{15, 10},
                    {30, 30},{40, 40}};

            String result = "";
            for (int i=0; i<points.length; ++i) {
                int index = getPixelIndex(width, points[i][0], points[i][1]);
                result = result + ":" + (arrImage[index] == Color.RED);
            }
            Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();

        }
    };

    public int getPixelIndex(int imageWidth, int pos_x, int pos_y) {
        return pos_y * imageWidth + pos_x;
    }

}

But the four results are all false which is not the results I expected. What are the errors for my code?


Solution

  • Your problem is this line:

    baseBitmap.setPixels(arrImage, 0, width, 0, 0, width, height);
    

    The setPixels() method replaces the pixel data in the Bitmap with the passed array, which, in this case, is all zeroes. It does not change the array's values, so they will still be all zeroes when you do your comparisons.

    You want the getPixels() method instead.