开发者

Android - SurfaceView (width, height) problem

开发者 https://www.devze.com 2023-02-12 15:36 出处:网络
Im new to android and im facing some issues... Im using a SurfaceView to extend my class. In my class i cant get width and height of the SurfaceView.

Im new to android and im facing some issues...

Im using a SurfaceView to extend my class. In my class i cant get width and height of the SurfaceView. It is always 0. Im trying to flick an image on the entire screen (surfaceView) but im unable to get its width and height.

Any suggestions?

Here is the code for SurfaceV开发者_如何学JAVAiew in main.xml:

<?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>


You could try implementing the surfaceChanged method (which is called any time the surface is resized, including when it is initialized):

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

Just do:

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


I have tried similar thing and posted on this thread Android: UI elements over canvas layer

Apart from above you would also need this to get height and width

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);
    }
}

if you dont want to pull your code in OnDraw you can try below code

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

But this will give you width height of whole visible area


The solution I found worked for me with this was to use getHeight() and getWidth() inside my SurafaceCreated method, after I started my thread. This allowed me to have the Height and Width of the surface view before any updating or drawing has occured.


Use surfaceView.getHolder().getSurfaceFrame() to get the Rect object with the sizes

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号