繁体   English   中英

修改位图图像

[英]Modifying bitmap image

我正在处理一个 android studio 项目。 我正在尝试在图像上选择用户触摸的像素,如图 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM