在Canvas,Android上更新Rect位置

时间:2015-03-01 00:59:03

标签: android android-canvas android-imageview

我想改变我在画布上添加的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;
        }

    }; 

}

我想改变我在画布上添加的Rect的位置

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

1 个答案:

答案 0 :(得分:1)

你可以使用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();