安卓自定义视图-实现图片堆叠效果
作者:访客发布时间:2023-10-26分类:程序开发学习浏览:221
导读:一、简介最近产品要实现一个UI类似于相册堆叠那种,一看就知道是相册,并且可以点进去查看图片,然后就用自定义视图的形式实现了下,效果图如下:二、原理其实它的原理也很简单,对照着下图来...
一、简介
最近产品要实现一个UI类似于相册堆叠那种,一看就知道是相册,并且可以点进去查看图片,然后就用自定义视图的形式实现了下,效果图如下:
二、原理
其实它的原理也很简单,对照着下图来看:
- 要实现堆叠的效果,我们需要先将视图的宽高获取到,如图最外边的矩形
- 然后根据最外边的矩形去将位图进行缩放
- 根据自己定义的偏移值,先画第三个图(红色),画到查看视图的右边,然后画中间,最后才画第一个位图
三、代码
class StackingView @JvmOverloads constructor(
private val context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
View(context, attrs, defStyleAttr) {
private val bitmapList = mutableListOf<Bitmap>()
//间距大小
private val padding = 120
init {
this.post {
val photo01 = BitmapFactory.decodeResource(context.resources, R.mipmap.photo_01)
val photo02 = BitmapFactory.decodeResource(context.resources, R.mipmap.photo_02)
val photo03 = BitmapFactory.decodeResource(context.resources, R.mipmap.photo_03)
//将Bitmap缩放统一大小
val reSizeWidth = width-padding
val reSizeHeight = height-padding
val scale01 = photo01.scale(reSizeWidth, reSizeHeight, true)
val scale02 = photo02.scale(reSizeWidth, reSizeHeight, true)
val scale03 = photo03.scale(reSizeWidth, reSizeHeight, true)
bitmapList.add(scale01)
bitmapList.add(scale02)
bitmapList.add(scale03)
invalidate()
}
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
val offset = padding/2f
if (bitmapList.isNotEmpty()) {
//这里倒序绘制
for (i in 2 downTo 0) {
canvas?.drawBitmap(bitmapList[i], offset*i, -offset*(i-2),null)
}
}
}
}
代码也很简单,这里就不多说了,总体来说这个功能还是很好实现的
- 程序开发学习排行
- 最近发表
-
- PSV游戏最简安装教程
- PSV中文游戏全集
- Otter Blocks Gutenberg Blocks,Page Builder for Gutenberg Editor amp; FSE 最好的WordPress常用插件下载 博客插件模块
- 支付表格、立即购买按钮和发票系统|GetPaid 最好的WordPress通用插件下载 博客插件模块
- Super Web Share Native Social Sharing Button 最好的WordPress常用插件下载 博客插件模块
- Post to PDF Exporter 最好的WordPress通用插件下载 博客插件模块
- 队列Ajax Calls性能最好的WordPress常用插件下载 博客插件模块
- Ultimate Tag Cloud Elementor Addon 最好的WordPress常用插件下载 博客插件模块
- 产品布局Elementor Addon 最好的WordPress常用插件下载 博客插件模块
- Shiptastic集成for UPS 最好的WordPress通用插件下载 博客插件模块