我有课,它以垂直方式画了许多十字架。我想学习如何做到这一点,所以我在这个简单的例子上试试:
public class Draw extends View {
Paint paint = new Paint();
public Draw(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
int x = 1;
for(int i = 0; i < 100; i++){
if (i%2 == 0) x = 2;
else x=1;
canvas.drawLine(0, 0 + x*i*20, 20, 20 + x*i*20, paint);
canvas.drawLine(20, 0 + x*i*20, 0, 20 + x*i*20, paint);
}
}
}
我想滚动它。
我用 MotionEvent.ACTION_MOVE 实现了 onTouchEvent:
public class DrawActivity extends Activity {
private Draw dv;
private float xDistance, yDistance, lastX, lastY;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dv = new Draw(this);
setContentView(dv);
}
public boolean onTouchEvent(MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case (MotionEvent.ACTION_MOVE):
final float curX = event.getX();
final float curY = event.getY();
xDistance += Math.abs(curX - lastX);
yDistance += Math.abs(curY - lastY);
lastX = curX;
lastY = curY;
if (xDistance > yDistance)
return false;
default:
return super.onTouchEvent(event);
}
}
}
但它不起作用。如何滚动画布?