我正在做一个应用程序,它在屏幕上用Touch事件画一个圆圈。下一个代码工作正常:
Class Punto extends view{
Paint paint;
Point point = new Point();
Public Punto(Context contex){
super(context);
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
paint.setColor(Color.BLUE);
canvas.drawCircle(point.x,point.y,10,paint);
}
@Override
public boolean onTouchEvent (MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
point.x = event.getX();
point.y = event.getY();
break;
}
return true;
}
class Point{
float x,y;
}
的活动:
public class Pintar extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Punto punto = new Punto(this);
setContentView(punto);
}
但是我需要在图片上绘制圆圈(在我的情况下是市场的平面),但我不知道如何做到这一点。
答案 0 :(得分:1)
只需扩展ImageView:
class Punto extends ImageView {
抱歉,我认为您发布的代码已经编译好了......
试试这个:
public class TouchImage extends ImageView {
Paint paint = new Paint();
Point point = new Point();
public TouchImage(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setColor(Color.BLUE);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(point.x, point.y, 10, 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;
}
}
使用这样的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Use your reverse package name, for instance "example.com" is -->
<com.example.TouchImage
android:id="@+id/touchImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/map" />
</LinearLayout>
触摸TouchImage时截取坐标的Activity:
public class Example extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TouchImage touchImage = (TouchImage) findViewById(R.id.touchImage);
touchImage.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// Call the existing onTouchEvent() in TouchImage,
// if it draws a circle fetch the coordinates
if(v.onTouchEvent(event)) {
// Do something with event.getX(), event.getY()
}
return true;
}
});
}
}