修改位图图像

Modifying bitmap image

我正在处理一个 android 工作室项目。我正在尝试 select 用户触摸图像上的像素,如图 1 所示。

我想在用户触摸的像素上添加(X),如何修改bitmap

这是图片。

如果我对你的问题理解正确,你想在每次用户点击位图时绘制 X,这就是你需要的:

    ImageView img;
    int clickCount = 0;
    Bitmap src;
    int colorTarget = Color.BLACK;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        img = findViewById(R.id.img);

        img.setOnTouchListener((v, event) -> {
            int x = (int) event.getX();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                drawXByPosition(img, src, x, y);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                clickCount++;
                if (clickCount % 2 == 0) colorTarget = Color.BLACK;
                else colorTarget = Color.WHITE;
            }
            return true;
        });


    }

    private void drawXByPosition(ImageView iv, Bitmap bm, int x, int y) {
        if (x < 0 || y < 0 || x > iv.getWidth() || y > iv.getHeight())
            Toast.makeText(getApplicationContext(), "Outside of ImageView", Toast.LENGTH_SHORT).show();
        else {
            int projectedX = (int) ((double) x * ((double) bm.getWidth() / (double) iv.getWidth()));
            int projectedY = (int) ((double) y * ((double) bm.getHeight() / (double) iv.getHeight()));
            src = drawX(src, "X", 44, colorTarget, projectedX, projectedY);
            img.setImageBitmap(src);
        }
    }

    public Bitmap drawX(final Bitmap src,
                        final String content,
                        final float textSize,
                        @ColorInt final int color,
                        final float x,
                        final float y) {
        Bitmap ret = src.copy(src.getConfig(), true);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas(ret);
        paint.setColor(color);
        paint.setTextSize(textSize);
        Rect bounds = new Rect();
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, x, y + textSize, paint);
        return ret;
    }