我开始使用Android学习画布绘图,我想制作一个简单的应用。
在app上启动一个所谓的'蛇'开始在屏幕上移动,当用户点击屏幕时,'蛇'会改变方向。
我很容易实现这一点,但有一点问题:
当用户点击屏幕时,蛇有时会在特定时刻改变方向,有时仅在几毫秒之后。因此,用户可以清楚地感觉到交互没有响应应该如此, 蛇的确切转弯时刻非常难以预测即使你非常努力。必须有一些其他方法比我更好地做到这一点。
请检查我的代码,我使用带有Runnable的处理程序移动蛇。(在画布上绘图,每次将其设置为视图的背景,即每次使用setContentView进行设置我的活动。
代码:
public class MainActivity extends Activity implements View.OnClickListener {
Paint paint = new Paint();
Canvas canvas;
View contentView; ///<The view to set by setContentView
int moveSize; ///<Sze in px to move drawer to draw another square
int leftIndex; ///<Indexes for square drawing
int topIndex;
int rightIndex;
int bottomIndex;
int maxBoundsX; ///<The max number of squares in X axis
int maxBoundsY; ///<The max number of squares in Y axis
int moveSpeedInMillis = 25; ///<One movement square per milliseconds
Bitmap bitmapToDrawOn; ///<We draw the squares to this bitmap
Direction currentDirection = Direction.RIGHT; ///< RIGHT,LEFT,UP,DOWN directions. default is RIGHT
Handler handler = new Handler(); ///<Handler for running a runnable that actually 'moves' the snake by drawing squares to shifted positions
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.i("runnable", "ran");
//Drawing a square to the current destination
drawRectPls(currentDirection);
//After some delay we call again and again and again
handler.postDelayed(runnable, moveSpeedInMillis);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*getting area properties like moveSize, and bounds*/
moveSize = searchForOptimalMoveSize();
maxBoundsX = ScreenSizer.getScreenWidth(this) / moveSize;
maxBoundsY = ScreenSizer.getScreenHeight(this) / moveSize;
Log.i("moveSize", "moveSize: " + moveSize);
Log.i("maxBounds: ", "x: " + maxBoundsX + " ; " + "y: " + maxBoundsY);
/*setting start pos*/
//We start on the lower left part of the screen
leftIndex = moveSize * (-1);
rightIndex = 0;
bottomIndex = moveSize * maxBoundsY;
topIndex = moveSize * (maxBoundsY - 1);
//Setting contentView, bitmap, and canvas
contentView = new View(this);
contentView.setOnClickListener(this);
bitmapToDrawOn = Bitmap.createBitmap(ScreenSizer.getScreenWidth(this), ScreenSizer.getScreenHeight(this), Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmapToDrawOn);
contentView.setBackground(new BitmapDrawable(getResources(), bitmapToDrawOn));
setContentView(contentView);
/*starts drawing*/
handler.post(runnable);
}
/**
* Draws a square to the next direction
*
* @param direction the direction to draw the next square
*/
private void drawRectPls(Direction direction) {
if (direction.equals(Direction.RIGHT)) {
leftIndex += moveSize;
rightIndex += moveSize;
} else if (direction.equals(Direction.UP)) {
topIndex -= moveSize;
bottomIndex -= moveSize;
} else if (direction.equals(Direction.LEFT)) {
leftIndex -= moveSize;
rightIndex -= moveSize;
} else if (direction.equals(Direction.DOWN)) {
topIndex += moveSize;
bottomIndex += moveSize;
}
addRectToCanvas();
contentView.setBackground(new BitmapDrawable(getResources(), bitmapToDrawOn));
Log.i("drawRect", "direction: " + currentDirection);
}
private void addRectToCanvas() {
paint.setColor(Color.argb(255, 100, 100, 255));
canvas.drawRect(leftIndex, topIndex, rightIndex, bottomIndex, paint);
}
/**
* Upon tapping the screen the the snake is changing direction, one way simple interaction
*/
@Override
public void onClick(View v) {
if (v.equals(contentView)) {
if (currentDirection.equals(Direction.RIGHT)) {
currentDirection = Direction.UP;
} else if (currentDirection.equals(Direction.UP)) {
currentDirection = Direction.LEFT;
} else if (currentDirection.equals(Direction.LEFT)) {
currentDirection = Direction.DOWN;
} else if (currentDirection.equals(Direction.DOWN)) {
currentDirection = Direction.RIGHT;
}
}
}
/**
* Just getting the size of a square. Searching for an integer that divides both screen's width and height
* @return
*/
private int searchForOptimalMoveSize() {
int i;
for (i = 16; i <= 64; i++) {
Log.i("iter", "i= " + i);
if (ScreenSizer.getScreenWidth(this) % i == 0) {
Log.i("iter", ScreenSizer.getScreenWidth(this) + "%" + i + " =0 !");
if (ScreenSizer.getScreenHeight(this) % i == 0) {
Log.i("iter", ScreenSizer.getScreenHeight(this) + "%" + i + " =0 !");
return i;
}
}
}
return -1;
}
/**
* Stops the handler
*/
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable);
}
}
E D I T:
我修改了我的代码,现在视图包含所有细节,我使用 onDraw 和 invalidate 方法,就像Philipp建议的那样。
结果稍好一些,但我仍然可以清楚地感觉到用户互动会导致方向变化。
也许我应该对线程做些什么?
public class SpiralView extends View implements View.OnClickListener {
int leftIndex; ///<Indexes for square drawing
int topIndex;
int rightIndex;
int bottomIndex;
int speedInMillis = 50;
int moveSize; ///<Sze in px to move drawer to draw another square
int maxBoundsX; ///<The max number of squares in X axis
int maxBoundsY; ///<The max number of squares in Y axis
Paint paint = new Paint();
Direction currentDirection = Direction.RIGHT; ///< RIGHT,LEFT,UP,DOWN directions. default is RIGHT
public void setUp(int moveSize, int maxBoundsX, int maxBoundsY) {
this.moveSize = moveSize;
this.maxBoundsX = maxBoundsX;
this.maxBoundsY = maxBoundsY;
this.leftIndex = moveSize * (-1);
this.rightIndex = 0;
this.bottomIndex = moveSize * (maxBoundsY);
this.topIndex = moveSize * (maxBoundsY - 1);
}
public SpiralView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnClickListener(this);
}
/**
* Draws a square to the next direction
*
* @param direction the direction to draw the next square
*/
private void drawOnPlease(Direction direction, Canvas canvas) {
if (direction.equals(Direction.RIGHT)) {
leftIndex += moveSize;
rightIndex += moveSize;
} else if (direction.equals(Direction.UP)) {
topIndex -= moveSize;
bottomIndex -= moveSize;
} else if (direction.equals(Direction.LEFT)) {
leftIndex -= moveSize;
rightIndex -= moveSize;
} else if (direction.equals(Direction.DOWN)) {
topIndex += moveSize;
bottomIndex += moveSize;
}
Log.i("drawRect", "direction: " + currentDirection);
Log.i("drawRect", "indexes: "+topIndex+" , "+rightIndex+" ," +bottomIndex+" , "+leftIndex);
addRectToCanvas(canvas);
}
private void addRectToCanvas(Canvas canvas) {
paint.setColor(Color.argb(255, 100, 100, 255));
canvas.drawRect(leftIndex, topIndex, rightIndex, bottomIndex, paint);
}
@Override
protected void onDraw(Canvas canvas) {
try {
drawOnPlease(currentDirection, canvas);
synchronized (this) {
wait(speedInMillis);
}
invalidate();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
if (currentDirection.equals(Direction.RIGHT)) {
currentDirection = Direction.UP;
} else if (currentDirection.equals(Direction.UP)) {
currentDirection = Direction.LEFT;
} else if (currentDirection.equals(Direction.LEFT)) {
currentDirection = Direction.DOWN;
} else if (currentDirection.equals(Direction.DOWN)) {
currentDirection = Direction.RIGHT;
}
//..?
invalidate();
}
}
答案 0 :(得分:1)
不要使用Handler绘制Canvas。 相反,您应该创建自定义视图并使用onDraw(Canvas画布)方法。 在这种方法中,您可以像现在一样在Canvas对象上绘制。 通过调用invalidate()方法,您可以触发一个新的onDraw()调用。 在onTouch()或onClick()函数中,您还可以通过调用invalidate()
来触发新的onDraw调用。class SnakView extends View {
@Override
protected void onDraw(Canvas canvas) {
// draw on canvas
invalidate();
}
@Override
public void onClick(View v) {
// handle the event
invalidate();
}
}
答案 1 :(得分:1)
魔术数是16毫秒,以便android重绘视图而不需要framedrops。
从Android开发者处查看此视频,并解释了这一点。 https://www.youtube.com/watch?v=CaMTIgxCSqU&index=25&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE
特别检查此视频 https://youtu.be/vkTn3Ule4Ps?t=54
它解释了如何使用画布剪切以便不在每个角色中绘制整个曲面,而螺母只画出需要绘制的内容。
答案 2 :(得分:0)
您可以尝试将android:hardwareAccelerated="true"
添加到您的清单中,或者添加到。
这适用于具有3.0 +的设备。
此外,您的目标api级别应为11。
然后它会更顺利地工作。