Android 相机库CameraView源码解析 (四) : 带滤镜预览

2024-01-01 13:52

本文主要是介绍Android 相机库CameraView源码解析 (四) : 带滤镜预览,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 前言

这段时间,在使用 natario1/CameraView 来实现带滤镜的预览拍照录像功能。
由于CameraView封装的比较到位,在项目前期,的确为我们节省了不少时间。
但随着项目持续深入,对于CameraView的使用进入深水区,逐渐出现满足不了我们需求的情况。
Github中的issues中,有些BUG作者一直没有修复。

那要怎么办呢 ? 项目迫切地需要实现相关功能,只能自己硬着头皮去看它的源码,去解决这些问题。
上篇文章,我们对带滤镜拍照的相关类有了大致的了解,这篇文章我们来看下CameraView是怎么实现带滤镜预览的。

以下源码解析基于CameraView 2.7.2

implementation("com.otaliastudios:cameraview:2.7.2")

为了在博客上更好的展示,本文贴出的代码进行了部分精简

在这里插入图片描述

2. 初始化CameraEngine

这部分逻辑和普通的预览一样 : Android 相机库CameraView源码解析 (一) : 预览 ,这里就略过了。

protected CameraEngine instantiateCameraEngine(Engine engine, CameraEngine.Callback callback) {if (mExperimental && engine == Engine.CAMERA2) {return new Camera2Engine(callback);} else {mEngine = Engine.CAMERA1;return new Camera1Engine(callback);}
}

3. 初始化CameraPreview

这里和不同预览不同的地方,是普通的预览创建的是SurfaceCameraPreview,而使用OpenGL的预览使用的是GlCameraPreview

protected CameraPreview instantiatePreview(@NonNull Preview preview,@NonNull Context context,@NonNull ViewGroup container) {switch (preview) {case SURFACE:return new SurfaceCameraPreview(context, container);case TEXTURE: {if (isHardwareAccelerated()) {// TextureView is not supported without hardware acceleration.return new TextureCameraPreview(context, container);}}case GL_SURFACE:default: {mPreview = Preview.GL_SURFACE;return new GlCameraPreview(context, container);}}
}

4. 初始化GLSurfaceView

GlCameraPreviewonCreateView()方法中,初始化了GLSurfaceView

4.1 初始化布局

在初始化布局中,通过findViewById获得了GLSurfaceView

protected GLSurfaceView onCreateView(@NonNull Context context, @NonNull ViewGroup parent) {ViewGroup root = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.cameraview_gl_view, parent, false);final GLSurfaceView glView = root.findViewById(R.id.gl_surface_view);//...省略了代码...在下文中详细说明parent.addView(root, 0);mRootView = root;return glView;
}

4.2 初始化Renderer

这里创建了Renderer类,Renderer是我们这里的关键,下文会详细再讲

final Renderer renderer = instantiateRenderer();
protected Renderer instantiateRenderer() {return new Renderer();
}

4.3 将GlCameraPreview和Renderer建立关联

这里调用了glView.setRenderer,将GlCameraPreviewRenderer建立了关联

glView.setEGLContextClientVersion(2);
glView.setRenderer(renderer);
glView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

5. Renderer类

Renderer类继承自GLSurfaceView.Renderer,有3个实现方法onSurfaceCreatedonSurfaceChangedonDrawFrame

public interface Renderer {void onSurfaceCreated(GL10 gl, EGLConfig config);void onSurfaceChanged(GL10 gl, int width, int height);void onDrawFrame(GL10 gl);
}

5.1 onSurfaceCreated

onSurfaceCreated里,我们会初始化GlTextureDrawer,并将Filter赋值给GlTextureDrawerGlTextureDrawer是负责绘制的类。
接着,由于我们使用的是GLSurfaceView.RENDERMODE_WHEN_DIRTY,所以要在合适的时机去调用requestRender来通知OpenGL渲染。

public void onSurfaceCreated(GL10 gl, EGLConfig config) {if (mCurrentFilter == null) {mCurrentFilter = new NoFilter();}mOutputTextureDrawer = new GlTextureDrawer();mOutputTextureDrawer.setFilter(mCurrentFilter);final int textureId = mOutputTextureDrawer.getTexture().getId();mInputSurfaceTexture = new SurfaceTexture(textureId);getView().queueEvent(new Runnable() {@Overridepublic void run() {for (RendererFrameCallback callback : mRendererFrameCallbacks) {callback.onRendererTextureCreated(textureId);}}});// Since we are using GLSurfaceView.RENDERMODE_WHEN_DIRTY, we must notify// the SurfaceView of dirtyness, so that it draws again. This is how it's done.mInputSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() {@Overridepublic void onFrameAvailable(SurfaceTexture surfaceTexture) {getView().requestRender(); // requestRender is thread-safe.}});
}

还有一点,会分发RendererFrameCallback回调的onRendererTextureCreated(),带滤镜拍照、录像都实现了RendererFrameCallback回调,从而来现实拍照和录像的功能。

  • SnapshotGlPictureRecordertake()的时候会添加该回调 : 是用来拍照的。
  • SnapshotVideoRecorder : 是用来录制视频的。

这两个我们后面的文章会讲,这里先略过。

5.2 onSurfaceChanged

5.2.1 设置尺寸

onSurfaceChanged方法中,会调用gl.glViewport,从而确定OpenGL窗口中显示的区域。
然后会调用Filter.setSize(),从而设置滤镜的尺寸。

public void onSurfaceChanged(GL10 gl, final int width, final int height) {gl.glViewport(0, 0, width, height);mCurrentFilter.setSize(width, height);if (!mDispatched) {dispatchOnSurfaceAvailable(width, height);mDispatched = true;} else if (width != mOutputSurfaceWidth || height != mOutputSurfaceHeight) {dispatchOnSurfaceSizeChanged(width, height);}
}
5.2.2 裁剪缩放计算

dispatchOnSurfaceAvailable()中,会将宽高赋值给mOutputSurfaceWidthmOutputSurfaceHeight

protected final void dispatchOnSurfaceAvailable(int width, int height) {mOutputSurfaceWidth = width;mOutputSurfaceHeight = height;if (mOutputSurfaceWidth > 0 && mOutputSurfaceHeight > 0) {crop(mCropCallback);}if (mSurfaceCallback != null) {mSurfaceCallback.onSurfaceAvailable();}
}

并调用crop进行裁剪缩放的计算,这里的mCroppingmCropScaleXmCropScaleY 都会在后面绘制的时候用到。

protected void crop(@Nullable final CropCallback callback) {if (mInputStreamWidth > 0 && mInputStreamHeight > 0 && mOutputSurfaceWidth > 0&& mOutputSurfaceHeight > 0) {float scaleX = 1f, scaleY = 1f;AspectRatio current = AspectRatio.of(mOutputSurfaceWidth, mOutputSurfaceHeight);AspectRatio target = AspectRatio.of(mInputStreamWidth, mInputStreamHeight);if (current.toFloat() >= target.toFloat()) {// We are too short. Must increase height.scaleY = current.toFloat() / target.toFloat();} else {// We must increase width.scaleX = target.toFloat() / current.toFloat();}mCropping = scaleX > 1.02f || scaleY > 1.02f;mCropScaleX = 1F / scaleX;mCropScaleY = 1F / scaleY;getView().requestRender();}if (callback != null) callback.onCrop();
}

5.3 onDrawFrame

在我们调用requestRender()后,就会触发onDrawFrame
onDrawFrame中,会操作OpenGL进行重新的绘制,并渲染到GlSurfaceView上,从而达到预览的效果。

5.3.1 进行裁剪、旋转等操作

这部分获取了transform 矩阵,然后根据之前计算出来的mCroppingmCropScaleXmCropScaleY 等参数进行裁剪和旋转的操作

final float[] transform = mOutputTextureDrawer.getTextureTransform();
mInputSurfaceTexture.updateTexImage();
mInputSurfaceTexture.getTransformMatrix(transform);
// LOG.v("onDrawFrame:", "timestamp:", mInputSurfaceTexture.getTimestamp());// For Camera2, apply the draw rotation.
// See TextureCameraPreview.setDrawRotation() for info.
if (mDrawRotation != 0) {Matrix.translateM(transform, 0, 0.5F, 0.5F, 0);Matrix.rotateM(transform, 0, mDrawRotation, 0, 0, 1);Matrix.translateM(transform, 0, -0.5F, -0.5F, 0);
}if (isCropping()) {// Scaling is easy, but we must also translate before:// If the view is 10x1000 (very tall), it will show only the left strip// of the preview (not the center one).// If the view is 1000x10 (very large), it will show only the bottom strip// of the preview (not the center one).float translX = (1F - mCropScaleX) / 2F;float translY = (1F - mCropScaleY) / 2F;Matrix.translateM(transform, 0, translX, translY, 0);Matrix.scaleM(transform, 0, mCropScaleX, mCropScaleY, 1);
}
5.3.2 进行绘制

接着,调用mOutputTextureDrawer.draw()从而重新进行绘制,并渲染到GlSurfaceView上,从而达到了预览的效果。

 mOutputTextureDrawer.draw(mInputSurfaceTexture.getTimestamp() / 1000L);
5.3.3 分发回调

最后会调用RendererFrameCallback.onRendererFrameRendererFrameCallback我们刚才已经说过了,带滤镜拍照、录像都实现了这个RendererFrameCallback回调,从而来现实拍照和录像的功能,这不是本文的重点,这里我们也先略过,后续文章中会详细讲解。

for (RendererFrameCallback callback : mRendererFrameCallbacks) {callback.onRendererFrame(mInputSurfaceTexture, mDrawRotation, mCropScaleX, mCropScaleY);
}

6. 其他

6.1 CameraView源码解析系列

Android 相机库CameraView源码解析 (一) : 预览-CSDN博客
Android 相机库CameraView源码解析 (二) : 拍照-CSDN博客
Android 相机库CameraView源码解析 (三) : 滤镜相关类说明-CSDN博客
Android 相机库CameraView源码解析 (四) : 带滤镜预览-CSDN博客
Android 相机库CameraView源码解析 (五) : 带滤镜拍照-CSDN博客
Android 相机库CameraView源码解析 (六) : 保存滤镜效果-CSDN博客

这篇关于Android 相机库CameraView源码解析 (四) : 带滤镜预览的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/559448

相关文章

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应

MyBatis中$与#的区别解析

《MyBatis中$与#的区别解析》文章浏览阅读314次,点赞4次,收藏6次。MyBatis使用#{}作为参数占位符时,会创建预处理语句(PreparedStatement),并将参数值作为预处理语句... 目录一、介绍二、sql注入风险实例一、介绍#(井号):MyBATis使用#{}作为参数占位符时,会

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧