设置 GLSurfaceView 以有限的 space 显示

set GLSurfaceView to show in a limited space

我正在研究 Android Studio 和 OpenGL ES。 我已经成功地显示了一个三角形,但我不知道如何在有限的 space(即 300dp x 300dp)中显示它。

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

我认为 setContentView(R.activity.something);并在 activity 中设置 GLSurfaceView(布局 size:300dp x 300dp)应该可行,但不知道如何实现。

您可以使用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 class:

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中class初始化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());
        ...
    } 
}

结果: