Android - SurfaceView(宽度,高度)问题

时间:2011-02-23 08:04:57

标签: android height width surfaceview

我是android的新手,我正面临一些问题......

我使用SurfaceView来扩展我的课程。 在我的课堂上,我无法获得SurfaceView的宽度和高度。 它始终为0.我试图在整个屏幕上轻弹图像(surfaceView),但我无法获得它的宽度和高度。

有什么建议吗?

以下是main.xml中SurfaceView的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <test.MyClass android:id="@+id/SurfaceView01"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
    </test.MyClass>
</LinearLayout>

4 个答案:

答案 0 :(得分:6)

您可以尝试实现surfaceChanged方法(在表面调整大小时调用,包括初始化时):

http://developer.android.com/reference/android/view/SurfaceHolder.Callback.html#surfaceChanged(android.view.SurfaceHolder,int,int,int)

只是做:

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // do whatever you want here with width and height;
}

答案 1 :(得分:4)

我尝试了类似的事情并发布在这个帖子Android: UI elements over canvas layer

除此之外,你还需要这个来获得高度和宽度

public void onDraw(Canvas canvas)
{
    this.canvas = canvas;

    if (!oneTime)
    {
        oneTime = true;
        screenWidth = getWidth();
        screenHeight = getHeight();
        Bitmap red = BitmapFactory.decodeResource(getResources(), R.drawable.image);
        red = Bitmap.createScaledBitmap(red, screenWidth , screenHeight , true);
    }
}

如果您不想在OnDraw中提取代码,可以尝试以下代码

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;

但这会给你整个可见区域的宽度高度

答案 2 :(得分:3)

我发现为我工作的解决方案是在我开始我的线程之后在我的SurafaceCreated方法中使用getHeight()和getWidth()。这使得我可以在任何更新或绘图出现之前获得表面视图的高度和宽度。

答案 3 :(得分:2)

使用surfaceView.getHolder().getSurfaceFrame()获取尺寸为

Rect对象
相关问题