Android-手撸抖音“潜艇大挑战”,最简单的Android自定义ListView下拉刷新与上拉加载

本文介绍了如何在Android中实现一个类似抖音的‘潜艇大挑战’游戏,涉及Camera2、自定义View、属性动画等技术。文章详细讲解了如何创建背景中的障碍物,包括障碍物的刷新、移动和删除,以及潜艇的动画效果和移动。此外,还涵盖了人脸识别和相机预览功能。这是一个综合性的Android开发实例,适合进阶学习。
摘要由CSDN通过智能技术生成

开发中会涉及以下技术的使用,没有高精尖、都是大路货:

  • 相机:使用Camera2完成相机的预览和人脸识别
  • 自定义View:定义并控制障碍物和潜艇
  • 属性动画:控制障碍物和潜艇的移动及各种动效

少啰嗦,先看东西!下面介绍各部分代码的实现。

2、后景(Background)

Bar

首先定义障碍物基类Bar,主要负责是将bitmap资源绘制到指定区域。由于障碍物从屏幕右侧定时刷新时的高度随机,所以其绘制区域的x、y、w、h需要动态设置

/**
* 屏幕下方障碍物
*/
class DnBar(context: Context, container: ViewGroup) : Bar(context) {

override val bmp = super.bmp.let {
Bitmap.createBitmap(
it, 0, 0, it.width, it.height,
Matrix().apply { postRotate(-180F) }, true
)
}

private val _srcRect by lazy(LazyThreadSafetyMode.NONE) {
Rect(0, 0, bmp.width, (bmp.height * (h / container.height)).toInt())
}

override val srcRect: Rect
get() = _srcRect
}

障碍物分为上方和下方两种,由于使用了同一张资源,所以绘制时要区别对待,因此定义了两个子类:UpBar和DnBar

/**
* 屏幕下方障碍物
*/
class DnBar(context: Context, container: ViewGroup) : Bar(context) {

override val bmp = super.bmp.let {
Bitmap.createBitmap(
it, 0, 0, it.width, it.height,
Matrix().apply { postRotate(-180F) }, true
)
}

private val _srcRect by lazy(LazyThreadSafetyMode.NONE) {
Rect(0, 0, bmp.width, (bmp.height * (h / container.height)).toInt())
}

override val srcRect: Rect
get() = _srcRect
}

下方障碍物的资源旋转180度后绘制

/**
* 屏幕下方障碍物
*/
class DnBar(context: Context, container: ViewGroup) : Bar(context) {

override val bmp = super.bmp.let {
Bitmap.createBitmap(
it, 0, 0, it.width, it.height,
Matrix().apply { postRotate(-180F) }, true
)
}

private val _srcRect by lazy(LazyThreadSafetyMode.NONE) {
Rect(0, 0, bmp.width, (bmp.height * (h / container.height)).toInt())
}

override val srcRect: Rect
get() = _srcRect
}

BackgroundView

接下来创建后景的容器BackgroundView,容器用来定时地创建、并移动障碍物。

通过列表barsList管理当前所有的障碍物,onLayout中,将障碍物分别布局到屏幕上方和下方

/**
* 后景容器类
*/
class BackgroundView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

internal val barsList = mutableListOf()

override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
barsList.flatMap { listOf(it.up, it.down) }.forEach {
val w = it.view.measuredWidth
val h = it.view.measuredHeight
when (it) {
is UpBar -> it.view.layout(0, 0, w, h)
else -> it.view.layout(0, height - h, w, height)
}
}
}

提供两个方法start和stop,控制游戏的开始和结束:

  • 游戏结束时,要求所有障碍物停止移动。
  • 游戏开始后会通过Timer,定时刷新障碍物

/**
* 游戏结束,停止所有障碍物的移动
*/
@UiThread
fun stop() {
_timer.cancel()
_anims.forEach { it.cancel() }
_anims.clear()
}

/**
* 定时刷新障碍物:
* 1. 创建
* 2. 添加到视图
* 3. 移动
*/


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值