package com.xypower.mpapp.v2; import android.content.Context; import android.opengl.GLSurfaceView; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class AutoFitGLView extends GLSurfaceView implements View.OnTouchListener { private float mAspectRatio; public AutoFitGLView(Context context) { this(context, null); } public AutoFitGLView(Context context, AttributeSet attrs) { super(context, attrs); setOnTouchListener(this); } private TouchListener touchListener; public void setAspectRatio(int width, int height){ mAspectRatio = (float)width / height; getHolder().setFixedSize(width, height); requestLayout(); } @Override public boolean onTouch(View v, MotionEvent event) { final int actionMasked = event.getActionMasked(); if (actionMasked != MotionEvent.ACTION_DOWN) { return false; } if (touchListener != null) { touchListener.onTouch(event, v.getWidth(), v.getHeight()); } return false; } public interface TouchListener { void onTouch(MotionEvent event, int width, int height); } public void setTouchListener(TouchListener touchListener) { this.touchListener = touchListener; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); if (mAspectRatio == 0) { setMeasuredDimension(width, height); }else { int newW,newH; float actualRatio; if (width > height) { actualRatio = mAspectRatio; }else { actualRatio = 1 / mAspectRatio; } if (width < height * actualRatio){ newH = height; newW = (int) (height * actualRatio); }else { newW = width; newH = (int) (width / actualRatio); } setMeasuredDimension(newW, newH); } } }