AndroidSurfaceView预览变形怎么解决-创新互联

这篇文章主要介绍“Android SurfaceView预览变形怎么解决”,在日常操作中,相信很多人在Android SurfaceView预览变形怎么解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Android SurfaceView预览变形怎么解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创新互联公司作为成都网站建设公司,专注成都网站建设、网站设计,有关企业网站设计方案、改版、费用等问题,行业涉及成都PVC花箱等多个领域,已为上千家企业服务,得到了客户的尊重与认可。

看下面这个回调:


  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Log.i(TAG, "surfaceChanged: " + width + " " + height);
  }

从上面的回调打印的数据知道其实取相近的比例解决不了根本问题


所以,对于此类的解决方法我只想说仅仅相近有神马用。

那么既然知道surfaceChanged的宽高就是SurfaceView的渲染宽高,那么想办法把surfaceChanged里的宽高比弄成和camera比例一样不就行了嘛,所以看SurfaceView的源码:

protected void updateWindow(boolean force, boolean redrawNeeded) {
    ...代码省略

    int myWidth = mRequestedWidth;
    if (myWidth <= 0) myWidth = getWidth();
    int myHeight = mRequestedHeight;
    if (myHeight <= 0) myHeight = getHeight();

    ...代码省略
      
    if (creating || formatChanged || sizeChanged
        || visibleChanged || realSizeChanged) {
      if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
          + "surfaceChanged -- format=" + mFormat
          + " w=" + myWidth + " h=" + myHeight);
      if (callbacks == null) {
        callbacks = getSurfaceCallbacks();
      }
      for (SurfaceHolder.Callback c : callbacks) {
        c.surfaceChanged(mSurfaceHolder, mFormat, myWidth, myHeight);
      }
    }
    
    ...代码省略
  }

可以看到宽高其实就是调用的View的getHeight和getWidth或者是mRequestedWidth和mRequestedHeight。


熟悉了View的自定义就知道getHeight和getWidth都是和View的onMeasure息息相关,所以想到重写onMeasure方法。


再从源码看到关于mRequestedWidth和mRequestedHeight的赋值

@Override
    public void setFixedSize(int width, int height) {
      if (mRequestedWidth != width || mRequestedHeight != height) {
        mRequestedWidth = width;
        mRequestedHeight = height;
        requestLayout();
      }
    }

以下是完整类代码:

public class ResizeAbleSurfaceView extends SurfaceView {

  private int mWidth = -1;
  private int mHeight = -1;

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

  public ResizeAbleSurfaceView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ResizeAbleSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (-1 == mWidth || -1 == mHeight) {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    else {
      setMeasuredDimension(mWidth, mHeight);
    }
  }

  public void resize(int width, int height) {
    mWidth = width;
    mHeight = height;
    getHolder().setFixedSize(width, height);
    requestLayout();
    invalidate(); 
  }
}

实例化的时候记得调用resize方法就好了。


注意和camera的预览尺寸比例一致,且宽高记得传正确,不然可能不全屏


到此,关于“Android SurfaceView预览变形怎么解决”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


文章名称:AndroidSurfaceView预览变形怎么解决-创新互联
文章路径:http://myzitong.com/article/eesho.html