更新 Canvas、Android 上的矩形位置

Update Rect Position on Canvas, Android

我想更改我在 Canvas

上添加的 Rect 的位置
public class RecActivity extends Activity {
    LinearLayout layout;
    ImageView view;
    Bitmap bg;
    Paint paint = new Paint();
    Rect rec = null;
    Canvas canvas; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //initialization of everything 
         view.setOnTouchListener(clickEvent);
         view.setOnLongClickListener(longclickEvent);
         view.setLongClickable(true);
         .......
    }

    private OnTouchListener clickEvent = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            xClick = event.getX();
            yclick = event.getY();

            return false;
        }
    };

    private OnLongClickListener longclickEvent = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            // TODO Auto-generated method stub
            messages.setText(xClick + ",L " + yclick);
            if (rec != null) { 

                   // here i want to give it a new position if it already exist
                    rec.set((int) xClick, (int) yclick, (int) xClick + 100,
                            (int) yclick + 200);

                    canvas.drawRect(rec, paint);


            } else {
                rec = new Rect((int) xClick, (int) yclick, (int) xClick + 100,
                        (int) yclick + 200);
                // rects.add(rec);
                canvas.drawRect(rec, paint);
            }

            view.invalidate();
            return true;
        }

    }; 

}

我想更改我在 Canvas

上添加的 Rect 的位置

我删除了部分代码以使其清晰易读。 提前致谢。

你可以使用canvas.translate(x,y);然后绘制。这是一些示例代码:

//Clear the canvas otherwise previous drawing will still be there
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
//save the current default drawing position
canvas.save();
canvas.translate(value,0);
canvas.drawBitmap(starBitmap, 0, 0, null);
//restore the default drawing position, otherwise will translate from the last traslated to position
canvas.restore();
//Need to manually call invalidate to redraw the view
mLittleChef.invalidate();