近期做柜端(Android)App,有個掃碼需求,隧將手機App工程中的掃碼組件拿來用嗽冒,就是zxing庫呀伙,集成的源碼补履,很老的版本了
問題1:左右翻轉問題
攝像頭對著我,我左移-像右移
嘗試多種方式剿另,無果箫锤,歷程如下:
方法 | SurfaceView | TextureView |
---|---|---|
view.setRotationY (180); | 無效果 | 鏡像翻轉 |
view.setsetScaleY(-1); | 無效果 | 鏡像翻轉 |
Animator | 有動畫效果贬蛙,無鏡像翻轉 | 有動畫效果,動畫后鏡像翻轉 |
Matrix | 無法獲取Matrix對象無法使用 | 鏡像翻轉 |
drawBitmap | 界面變成白色谚攒,畫布上繪制的文字鏡像 | 無法獲取SurfaceHoder的lockCanvas方法 |
Camera.previewCallback | 與項目實際使用不符未嘗試 | 與項目實際使用不符未嘗試 |
解決1:鏡像翻轉問題 即 解決畫面預覽問題
zxing這庫幾層handler通信確實看暈阳准,簡直就是對未知的不安,無從下手馏臭。最先就是直白的啥問題搜啥野蝇,反正AI答的也不太好使。了解了一下zxing源碼括儒,知道大致原理流程绕沈,參考該文章,有種感覺帮寻,畫面預覽跟真的碼識別沒多大關系乍狐,然后就了解用使用TextureView替代SurfaceView
方法1:先獲取SurfaceView的Surface,并將其傳遞給TextureView帖汞。預覽畫面白屏
https://blog.51cto.com/u_16175526/10345087
// 獲取SurfaceView的Surface
SurfaceView surfaceView = findViewById(R.id.surfaceView);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
Surface surface = surfaceHolder.getSurface();
// 創(chuàng)建TextureView并設置Surface
TextureView textureView = new TextureView(this);
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface newSurface = new Surface(surfaceTexture);
// 使用新的Surface繪制圖像
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {}
});
// 將TextureView添加到布局中
ViewGroup parent = (ViewGroup) surfaceView.getParent();
int index = parent.indexOfChild(surfaceView);
parent.removeView(surfaceView);
parent.addView(textureView, index);
方法2:https://blog.csdn.net/oDongFangZhiZi/article/details/73867785课竣。成功
使用mCamera.setPreviewTexture((SurfaceTexture) surfaceTexture);
替代mCamera.setPreviewDisplay((SurfaceHolder) msg.obj);
褐墅。
原本覺得預覽組件耦合很深,不容易替換惜傲。但是先換再說,找到setPreviewDisplay贝攒,就是camera的核心方法openDriver
操漠。
改起來:
public synchronized void openDriver(SurfaceTexture holder),該調整的入?yún)⒄{整一下
頁面上原本Camera.CallBack的實現(xiàn)邏輯對應的挪到TextureView.SurfaceTextureListener的實現(xiàn)方法中
就這饿这,可以了
問題2:橫屏設備浊伙,預覽畫面水平拉伸
camera.setDisplayOrientation(270);
設置橫屏展示
水平拉伸問題有個取巧辦法:
...
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
...>
<TextureView
...
android:layout_marginTop="-340dp"
android:layout_marginBottom="-340dp"/>
...
硬給它顯示成豎屏的,但只可見部分預覽畫面