Android中的metadataOutputRectConverted(FromLayerRect:) [英] metadataOutputRectConverted(fromLayerRect:) in Android

查看:72
本文介绍了Android中的metadataOutputRectConverted(FromLayerRect:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我在从相机预览中裁剪矩形时遇到问题。基本上,我已经使用fotoapparat设置了相机,其中我将预览的scaleType设置为ScaleType.CenterCrop

因为这会拉伸预览以填满屏幕(我有一个全屏肖像模式相机预览),所以我不知道相机的真实宽度。因此,现在当我想要根据屏幕上显示的矩形的大小从图像中剪切矩形时,它的宽度无法正确裁剪。

我在SWIFT(IOS)中遇到了类似的问题,但能够使用metadataOutputRectConverted(fromLayerRect:)

解决

我假设我必须做一些事情,比如找出相机预览层的真实大小,以便包括为填充屏幕而裁剪的任何内容,并在此基础上计算相对于相机预览的新矩形宽度。

关于这一点,请参阅我的previous question,但为了快速。就像在这篇文章中(见截图),宽度没有按预期裁剪。

当前的裁剪方法,其中位图是我们拍照后收到的图像,cameraView基本上就是屏幕的宽度和高度,cropRectFrame是屏幕中我想要裁剪其中的任何内容的矩形。

    private fun cropImage(bitmap: Bitmap, cameraFrame: View, cropRectFrame: View): Bitmap {

        val heightOriginal = cameraFrame.height
        val widthOriginal = cameraFrame.width

        val heightFrame = cropRectFrame.height
        val widthFrame = cropRectFrame.width
        val leftFrame = cropRectFrame.left
        val topFrame = cropRectFrame.top

        val heightReal = bitmap.height
        val widthReal = bitmap.width

        val widthFinal = (widthFrame * widthReal / widthOriginal)
        val heightFinal = (heightFrame * heightReal / heightOriginal)
        val leftFinal = (leftFrame * widthReal / widthOriginal)
        val topFinal = (topFrame * heightReal / heightOriginal)

        return Bitmap.createBitmap(
            bitmap, leftFinal, topFinal, widthFinal, heightFinal
        )
    }

感谢任何帮助。

推荐答案

我用以下代码解决了这个问题。

private fun cropImage(bitmap: Bitmap, cameraFrame: View, cropRectFrame: View): Bitmap {
    val scaleFactor: Double; val widthOffset: Double; val heightOffset: Double

    if (cameraFrame.height * bitmap.width > cameraFrame.height * bitmap.width) {
        scaleFactor = (bitmap.width).toDouble() / (cameraFrame.width).toDouble()
        widthOffset = 0.0
        heightOffset = (bitmap.height - cameraFrame.height * scaleFactor) / 2
    } else {
        scaleFactor = (bitmap.height).toDouble() / (cameraFrame.height).toDouble()
        widthOffset = (bitmap.width - cameraFrame.width * scaleFactor) / 2
        heightOffset = 0.0
    }

    val newX = cropRectFrame.left * scaleFactor + widthOffset
    val newY = cropRectFrame.top * scaleFactor + heightOffset
    val width = cropRectFrame.width * scaleFactor
    val height = cropRectFrame.height * scaleFactor

    return Bitmap.createBitmap(bitmap, (newX).toInt(), (newY).toInt(), (width).toInt(), (height).toInt())

}

这篇关于Android中的metadataOutputRectConverted(FromLayerRect:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆