How to draw a Line in ImageView on Android?

前端 未结 4 1665
無奈伤痛
無奈伤痛 2020-12-05 15:50

I\'d Like to know how to draw a Line on ImageView as user swipe their finger ?

Could any body explain this ? Or perhaps any Link to get start on this.

4条回答
  •  执念已碎
    2020-12-05 16:52

    This is a complete example of how you can draw green rectangle over another image:

    package CustomWidgets;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    
    /**
     * Allows to draw rectangle on ImageView.
     *
     * @author Maciej Nux Jaros
     */
    public class DrawImageView extends ImageView {
        private Paint currentPaint;
        public boolean drawRect = false;
        public float left;
        public float top;
        public float right;
        public float bottom;
    
        public DrawImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            currentPaint = new Paint();
            currentPaint.setDither(true);
            currentPaint.setColor(0xFF00CC00);  // alpha.r.g.b
            currentPaint.setStyle(Paint.Style.STROKE);
            currentPaint.setStrokeJoin(Paint.Join.ROUND);
            currentPaint.setStrokeCap(Paint.Cap.ROUND);
            currentPaint.setStrokeWidth(2);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            if (drawRect)
            {
                canvas.drawRect(left, top, right, bottom, currentPaint);
            }
        }
    }
    

    When you have this defined you can replace ImageView with above View (widget) for example:

    
    

    Then you can use this for example in touch event of the activity that controls the layout:

        mapImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                DrawImageView drawView = (DrawImageView) v;
    
                // set start coords
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    drawView.left = event.getX();
                    drawView.top = event.getY();
                // set end coords
                } else {
                    drawView.right = event.getX();
                    drawView.bottom = event.getY();
                }
                // draw
                drawView.invalidate();
                drawView.drawRect = true;
    
                return true;
            }
        });
    

    Of course you could make some getters and setters and other Java over-engineering routines ;-).

提交回复
热议问题