android xml surfaceview,你可能不知道的Android SurfaceView的兄弟神奇的TextureView详解

原标题:你可能不知道的Android SurfaceView的兄弟神奇的TextureView详解

如果你想显示一段在线视频或者任意的数据流比如视频或者OpenGL 场景,你可以用android中的TextureView做到。

TextureView的兄弟SurfaceView

应用程序的视频或者opengl内容往往是显示在一个特别的UI控件中:SurfaceView。SurfaceView的工作方式是创建一个置于应用窗口之后的新窗口。这种方式的效率非常高,因为SurfaceView窗口刷新的时候不需要重绘应用程序的窗口(android普通窗口的视图绘制机制是一层一层的,任何一个子元素或者是局部的刷新都会导致整个视图结构全部重绘一次,因此效率非常低下,不过满足普通应用界面的需求还是绰绰有余),但是SurfaceView也有一些非常不便的限制。

因为SurfaceView的内容不在应用窗口上,所以不能使用变换(平移、缩放、旋转等)。也难以放在ListView或者ScrollView中,不能使用UI控件的一些特性比如View.setAlpha()。

为了解决这个问题 Android 4.0中引入了TextureView。

TextureView

与SurfaceView相比,TextureView并没有创建一个单独的Surface用来绘制,这使得它可以像一般的View一样执行一些变换操作,设置透明度等。另外,Textureview必须在硬件加速开启的窗口中。

TextureView的使用非常简单,你唯一要做的就是获取用于渲染内容的SurfaceTexture。具体做法是先创建TextureView对象,然后实现SurfaceTextureListener接口,代码如下:

525256ca6757de9518e7b47ac6345d16.png

Activity implements了SurfaceTextureListener接口因此activity中需要重写如下方法:

08097ff6f8a16a6e6c264826049174a4.png

TextureView可以使用setAlpha和setRotation方法达到改变透明度和旋转的效果。

myTexture.setAlpha(1.0f);

myTexture.setRotation(90.0f);

除了上面的方法之外,TextureView 还有如下方法:

序号

方法&描述

1

getSurfaceTexture()

This method returns the SurfaceTexture used by this view.

2

getBitmap(int width, int height)

This method returns Returns a Bitmap representation of the content of the associated surface texture.

3

getTransform(Matrix transform)

This method returns the transform associated with this texture view.

4

isOpaque()

This method indicates whether this View is opaque.

5

lockCanvas()

This method start editing the pixels in the surface

6

setOpaque(boolean opaque)

This method indicates whether the content of this TextureView is opaque.

7

setTransform(Matrix transform)

This method sets the transform to associate with this texture view.

8

unlockCanvasAndPost(Canvas canvas)

This method finish editing pixels in the surface.

例子

下面的例子演示了如何使用TextureView类,我们创建了一个可以在TextureView中预览Camera的demo,可以改变它的角度以及方向。当然程序需要运行在有摄像头的设备上。

下面是MainActivity.java中的代码:

31170d5c4ed37e99ad2c7df48434adb9.png

da3971fe92bea6cb4b637d0f29facd0d.png

activity_main.xml

1a182724d4217d4d89c19a13c8a78836.png

AndroidManifest.xml

fbb5e29e8b3e65a83d0b2e82f6a2b241.png

不同参数下的截图:

myTexture.setAlpha(0.5f);

myTexture.setRotation(45.0f);

cbf05258f9f3a9f945a5bd38d1640d54.png

myTexture.setAlpha(1.5f);

myTexture.setRotation(45.0f);

a0e9eaeb418cfbc3355118aea90a6a3b.png

myTexture.setAlpha(1.0f);

myTexture.setRotation(90.0f);

6813908e9cbc1d8b6e74eeaed2566d76.png

看完本文有收获?请分享给更多人

Java和Android架构

公众号:JANiubility返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值