下面的程序画了一点云
在用户触摸的位置。
如果你用 替换/*A*/
,///*A*/
它运行良好。
但它是缓慢的。因此(没有注释掉/*A*/s
)绘图是在一个单独的线程上完成的。为了保持流畅的交互,当用户移动指针时线程会被中断。
您将如何修改此代码以正确绘制单独的线程?
public class MyView extends View {
/*A*/ protected MyDrawThread myDrawThread;
protected float x, y;
protected Paint paint = new Paint();
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
/*A*/ myDrawThread = new MyDrawThread();
}
@Override protected void onDraw(Canvas canvas)
{
/*A*/ if( myDrawThread.isAlive() )
/*A*/ myDrawThread.interrupt();
/*A*/
/*A*/ myDrawThread.setCanvas( canvas );
/*A*/ myDrawThread.start();
/*A*/ }
/*A*/
/*A*/ class MyDrawThread extends Thread {
/*A*/ private Canvas canvas;
/*A*/
/*A*/ public MyDrawThread() {
/*A*/ super();
/*A*/ }
/*A*/ public void setCanvas( Canvas cnvs ) {
/*A*/ canvas = cnvs;
/*A*/ }
/*A*/ public void run()
/*A*/ {
for(int i=0;i<10000;++i) {
double angle = (double) (Math.random() * 2.0 * Math.PI);
float distance = (float) (Math.random() * getWidth()/25.0f);
float dx = (float) (distance*Math.cos(angle));
float dy = (float) (distance*Math.sin(angle));
canvas.drawCircle(x+dx, y+dy, 0.1f, paint);
}
/*A*/ }
}
@Override public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
invalidate();
return true;
}
}
布局activity_main
仅包括
<.MyView
android:id="@+id/myView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
并且活动设置视图通过
setContentView(R.layout.activity_main);