将GLSurfaceView设置为在有限的空间中显示

问题描述 投票:1回答:1

我正在使用Android Studio和OpenGL ES。我已经成功制作了一个三角形,但是我不知道如何在有限的空间(即300dp x 300dp)中显示它。

gLView = new MyGLSurfaceView(this);
setContentView(gLView);

我认为setContentView(R.activity.something);并在活动中设置GLSurfaceView(布局尺寸:300dp x 300dp)应该可以,但不知道如何。

java android android-studio opengl-es
1个回答
1
投票

您可以使用surfaceView创建布局,例如activity_gl.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        tools:context=".activities.OpenGLActivity">
    <com.app.LimitedSurfaceView
        android:id="@+id/oglView"
        android:layout_width="300dp"
        android:layout_height="300dp"/>
    <!-- other elements -->
</androidx.constraintlayout.widget.ConstraintLayout>

并创建LimitedSurfaceView类:

package com.app;

public class LimitedSurfaceView extends GLSurfaceView {
    private SceneRenderer renderer;

    public LimitedSurfaceView(Context context) {
        super(context);
    }

    public LimitedSurfaceView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public void init(Context context) {
        setPreserveEGLContextOnPause(true);
        setEGLContextClientVersion(2); // or setEGLContextClientVersion(3)
        renderer = new SceneRenderer(context);
        setRenderer(renderer);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        ...
    }
}

然后在OpenGLActivity类中初始化limitedSurfaceView:

package com.app.activities

public class OpenGLActivity extends AppCompatActivity {
    private LimitedSurfaceView limitedSurfaceView;

    @Override
    protected void onCreate(Bundle state) { 
        super.onCreate(state);
        setContentView(R.layout.activity_gl);
        limitedSurfaceView = findViewById(R.id.oglView);
        limitedSurfaceView.init(this.getApplicationContext());
        ...
    } 
}

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.