简体   繁体   中英

Modifying bitmap image

I'm working with an android studio project. I'm trying to select user touched pixel on an image, as shown Fig 1.

I want to add (X) on a pixel touched by the user, how can I make it by modifying bitmap ?

This is image.

If I understand your question correctly, you want to draw X in each time the user click on Bitmap, here's what you need :

在此处输入图片说明

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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