Android在SurfaceView和Canvas上的绘图

12

我有一个“简单”的问题。我尝试在SurfaceView上进行绘制。布局XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <SurfaceView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/imagesurface"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:background="#00ff00">
    </SurfaceView>

</LinearLayout>

Activity是SurfaceHolder.Callback:

public class OpenCvonAndroidGTDforHOGActivity extends Activity implements SurfaceHolder.Callback{

    private SurfaceHolder _surfaceHolder;
    private SurfaceView _surfaceView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        _surfaceView = (SurfaceView)findViewById(R.id.imagesurface);
        _surfaceHolder = _surfaceView.getHolder();
        _surfaceHolder.addCallback(this);
        _surfaceView.setWillNotDraw(false);

    }

    protected void onDraw(Canvas canvas) {
        canvas.drawRGB(255, 0, 255);            
    }

    public void surfaceCreated(SurfaceHolder holder) {
        Canvas canvas = null;
        try {
            canvas = holder.lockCanvas();
            synchronized(holder) {
                onDraw(canvas);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }


    public void showToast(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
}

如果我在onDraw(...)中调用

_surfaceview.setBackground(Color.RED) 它能正常工作。但是

canvas.drawRGB(255, 0, 255) 却无法正常工作 :(


这个回答解决了你的问题吗?在Android中绘制到SurfaceView - General Grievance
2个回答

5

SurfaceView 是由当前布局中的 View 和位于布局下方的表面(surface)组成。如果您将背景设置为视图,您将看不到表面上发生的任何事情。


-2

你试过了吗?

yourHolder.unlockCanvassAndPost(your_canvas);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接