使用与背景颜色不同的颜色绘制线条。然后将位图放在画布中的数组中。如果数组中给定点的颜色与线条的颜色相同,则该点在该线条中。另外,我不想在我的应用程序中显示画布。
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;
}
}
但是四个结果都是false
,这不是我预期的结果。
我的代码有什么错误?
答案 0 :(得分:0)
你的问题就在这一行:
baseBitmap.setPixels(arrImage, 0, width, 0, 0, width, height);
setPixels()
方法用传递的数组替换Bitmap
中的像素数据,在这种情况下,该数组全为零。它不会更改数组的值,因此在进行比较时它们仍将全为零。
您需要getPixels()
方法。