はじめに
初投稿です。今回はテストも兼ねてAndroidのカメラプレビューの回転処理をどうするか問題について書いてみます。
私自身初心者ですので内容も初心者向けかもしれませんが、少しでも参考になれば幸いです。
スマホ画面の向きを取得
fun rotationView(){
appRotation = when(windowManager.defaultDisplay.rotation){//アプリ画面の向き
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> //ありえない
}
・
・
縦向きと横向きの2通りにしてもいいです。
回転時ビューをリサイズするので倍率を決める
後述しますが、videoWidth,videoHeightにはSurfaceTextureの横,縦のサイズが入っています。
・
・
val scaleX:Float = when{
appRotation == 0 || appRotation == 180 -> videoWidth.toFloat() / videoWidth.toFloat()//1.0倍(縦向きならリサイズしない)
appRotation == 90 ||appRotation == 270 -> videoWidth.toFloat() / videoHeight.toFloat()//X/Y倍(横向きならリサイズする)
else -> 1.0f//ありえない
}
val scaleY:Float = when{
appRotation == 0 || appRotation == 180 -> videoHeight.toFloat() / videoHeight.toFloat()//1.0倍(縦向きならリサイズしない)
appRotation == 90 || appRotation == 270 -> videoHeight.toFloat() / videoWidth.toFloat()//Y/X倍(横向きならリサイズする)
else -> 1.0f//ありえない
}
・
・
scaleXが横軸(スマホの短い方),scaleYが縦軸(スマホの長い方)の倍率です。
最後にビューを回転,リサイズする
・
・
val matrix = Matrix()
matrix.postRotate(-appRotation.toFloat(),videoWidth * 0.5f,videoHeight * 0.5f)//px,pyを起点にスマホの回転と逆回転させる
matrix.postScale(scaleX,scaleY,videoWidth * 0.5f,videoHeight * 0.5f)//px,pyを起点にリサイズ
mainView.setTransform(matrix)
}
postRotateでスマホの回転方向と逆向きにビューを回転させます。ただ回転させるだけだとビューが引き延ばされた感じになってしまうので、postScaleで横向きのときはX軸にX/Yを掛けてYの長さに、Y軸にY/Xを掛けてXの長さにリサイズします。
単純にビューの縦横のサイズを指定できれば早いんですけどね...。
あとはsurfaceTextureListenerでサイズを変更する
private val surfaceTextureListener = object:TextureView.SurfaceTextureListener{
override fun onSurfaceTextureAvailable(texture:SurfaceTexture, width: Int, height: Int) {
//有効になった時
videoWidth = width
videoHeight = height
rotationView()
}
override fun onSurfaceTextureSizeChanged(texture:SurfaceTexture, width: Int, height: Int) {
//サイズが変わった時
videoWidth = width
videoHeight = height
rotationView()
}
override fun onSurfaceTextureUpdated(texture:SurfaceTexture) {
//更新時
}
override fun onSurfaceTextureDestroyed(texture:SurfaceTexture): Boolean {
//破棄された時
}
}
ビューのサイズが変わったときもwidthとheightを渡すなりすればちゃんとリサイズしてくれます。
もっとこうした方がいいよってのがあれば是非教えてください!