public class BackgammonBoardView extends SurfaceView implements SurfaceHolder.Callback {
/***
* @author
* The threads class definition
*/
class BBVThread extends Thread
{
//mSurfaceHolder and mHandler are part of the thread.
//mContext is part of the container SurfaceView
private SurfaceHolder mSurfaceHolder;
private Handler mHandler;
//The threads constructor
public BBVThread(SurfaceHolder surfaceHolder, Context context,
Handler handler) {
Log.d(TAG,"BBVThread. Constructor.");
mSurfaceHolder = surfaceHolder;
mHandler = handler;
mContext = context;
mDiceCup = context.getResources().getDrawable(
R.drawable.dicecup);
}
@Override
public void run() {
Log.d(TAG,"BBVThread. run.");
Canvas canvas = null;
try {
canvas = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
Log.d(TAG,"Draw the dice cup...");
mDiceCup.setBounds(0, 0, 120,120);
mDiceCup.draw(canvas);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (canvas != null) {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}//end run
}
/****
* end of the BBVThread class
*/
/* ########################################
* # BackgammonBoardView Member Variables #
* ######################################## */
private Drawable mDiceCup;
/*
* End BackGammonBoardView Member Variables
*/
public BackgammonBoardView(Context context, AttributeSet attrs)
{
super(context, attrs);
Log.d(TAG,"SurfaceView Constructor.");
//register out interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
thread = new BBVThread(holder, context, new Handler(){
@Override
public void handleMessage(Message m) {
}
});
setFocusable(true); // make sure we get key events
}
@Override
public void surfaceCreated(SurfaceHolder arg0)
{
//Start the thread. This will initiate run which will do the first draw
thread.start();
//Norify that the surface has been created
Log.d(TAG,"SurfaceView. surfaceCreated.");
}
}
我遵循了我在LunarLander示例中看到的那种代码。我创建了一个res / drawable文件夹。以前我在res / drawable-hdpi中的图像,但是当我没有看到绘制到画布上的图像时,我创建了res / drawable并将.png复制到该文件夹中。我对R.drawable.dicecup的调用解决了,没有任何语法错误。我的图像编辑器中的图像大小为120 x 120像素。当我打开应用程序并且没有任何地方绘制骰子杯图像时,我感到很惊讶。可能有什么不对?
该线程实际上是在surfaceCreated方法中启动的。我从运行中获取了Log.d,所以我知道运行正在执行。据我所知,没有任何错误,程序没有崩溃或任何事情都没有被绘制。
我已经尝试将绘图移回UI线程,但我仍然没有看到任何内容。
P.S。结果证明这是我的错。 Bitmap从我刚用于背景图像的矩形中删除的线程中得到了很好的结果,我还没有发现它。现在我应该知道如何绘制位图以发现这些类型的问题。为了让事情变得简单,我创建了res / drawables并从那里加载图像。
答案 0 :(得分:1)
看起来你试图在UI线程以外的线程上调用draw。如果这就是你正在做的事情,那就是它无法正常工作的原因。根据{{3}},您无法在非UI线程上执行任何UI工作。