surfaceview上的Drawtext仅适用于模拟器,但不适用于设备

时间:2013-04-02 21:00:24

标签: android android-canvas surfaceview drawtext

我在SurfaceView上使用canvas.drawText,输出在模拟器上看起来正确但是当我将应用程序部署到我的设备(三星Galaxy S3)时,文本从上到下写成:

T
E
s
t

Wrong output on Device Samsung Galaxy S3

看起来在文本的每个字符后添加换行符。

如果设备是否是风景并不重要,它就永远不会工作,我无法弄清楚原因。

我做错了什么?

Emulator shows output correctly

在AndroidManifest.xml中我使用:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="8" />

我正在使用的代码:

public class MainActivity extends Activity {

    DemoView renderView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        renderView = new DemoView(this);
        setContentView(renderView);
    }

    @Override
    public void onResume() {
        super.onResume();
        renderView.resume();
    }

    @Override
    public void onPause() {
        super.onPause();
        renderView.pause();
    }

    private class DemoView extends SurfaceView implements Runnable{
        Thread renderThread = null;
        SurfaceHolder holder;
        volatile boolean running = false;

        public DemoView(Context context){
            super(context);
            this.holder = getHolder();
        }

        public void resume() {
            running = true;
            renderThread = new Thread(this);
            renderThread.start();
        }

        public void run() {
            Canvas canvas;

            while(running) {
                if(!holder.getSurface().isValid())
                    continue;
                Paint test = new Paint(Color.YELLOW);
                test.setColor(Color.YELLOW);
                canvas = holder.lockCanvas();
                canvas.drawText("TEst", 10, 10, test);
                holder.unlockCanvasAndPost(canvas);
            }
        }

        public void pause() {
            running = false;
            while(true) {
                try {
                    renderThread.join();
                    break;
                } catch (InterruptedException e) { // retry
                }
            }
        }
    }
}

感谢您的帮助! Stephoid

2 个答案:

答案 0 :(得分:1)

您对SurfaceHolder的使用非常奇怪。我认为意外的行为是由于这一点。这就是我过去使用SurfaceView的方法:

public void run() {
        Canvas canvas;

        while(running) {
            try {
              if(!holder.getSurface().isValid())
                continue;
              canvas = holder.lockCanvas();
              synchronized (surface) {
                //Code to draw text/etc
              }
            } catch (...) {
            } finally {
              holder.unlockCanvasAndPost(canvas);
            }                
        }
    }

请注意您缺少lockCanvas表达式以实际指定画布并与unlockCanvasAndPost

配对

答案 1 :(得分:0)

问题在于我初步化了Paint test错误!

WRONG:

Paint test = new Paint(Color.YELLOW);

正确:

Paint test = new Paint();
test.setColor(Color.YELLOW);

一个很小的东西,但效果很好!