如何在Android中的特定点触摸时在imageview上绘制圆圈

时间:2013-09-21 05:39:56

标签: android android-imageview

这是我在androidmanifest文件中的ImageView。

<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="+id/imageview1"></ImageView>

我在触摸时在imageview上绘制了一个圆圈,但是在左上角绘制了圆圈。

这是我的代码:

ImageView myimage=(ImageView)findViewById(R.id.imageview1);
myimage.setImageResource(R.drawable.penguins);

BitmapDrawable bmpdraw=(BitmapDrawable)myimage.getDrawable();
Bitmap bmp=bmpdraw.getCopy().config();
Canvas m_canvas=new Canvas(bmp);


public void onTouch(View v,MotionEvent event){
int x=event.getX();
int y=event.getY();
canvas.drawCircle(x,y,10,paint);
myimage.setBitmap(bmp);

}

我发现与imageview相比,画布位置不同。

1 个答案:

答案 0 :(得分:3)

尝试以下代码。 my_canvas.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


</RelativeLayout>

MyCanvas.java

public class MyCanvas extends Activity {
    private RelativeLayout rl_Main;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_read);
        rl_Main = (RelativeLayout) findViewById(R.id.rl_main);
        rl_Main.addView(new MyView(this));
    }

    class MyView extends View{


        Paint paint = new Paint();
        Point point = new Point();
        public MyView(Context context) {
            super(context);
            paint.setColor(Color.RED);
            paint.setStrokeWidth(15);
            paint.setStyle(Style.STROKE);
        }

        @Override
        protected void onDraw(Canvas canvas) {
              Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.images);
              canvas.drawBitmap(b, 0, 0, paint);
              canvas.drawCircle(point.x, point.y, 100, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                point.x = event.getX();
                point.y = event.getY();

            }
              invalidate();
            return true;

        }

    }
     class Point {
            float x, y;
        }
}