Android自定义View-实现图片堆叠效果

一、简介

最近产品要实现一个UI类似于相册堆叠那种,一看就知道是相册,并且可以点进去查看图片,然后就用自定义View的形式实现了下,效果图如下:

二、原理

其实它的原理也很简单,对照着下图来看:

  1. 要实现堆叠的效果,我们需要先将View的宽高获取到,如图最外边的矩形
  2. 然后根据最外边的矩形去将Bitmap进行缩放
  3. 根据自己定义的偏移值,先画第三个图(红色),画到View视图的右边,然后画中间,最后才画第一个Bitmap

三、代码

kotlin 复制代码
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)
            }
        }
    }

}

代码也很简单,这里就不多说了,总体来说这个功能还是很好实现的

相关推荐
plainGeekDev28 分钟前
kapt 替换为 KSP
android·java·kotlin
蜡台38 分钟前
通过Gradle脚本声明更改Java变量
android·java·开发语言·python·kotlin·gradle·groovy
阿pin4 小时前
Android随笔-SharedPreferences
android·sp
茶栀(*´I`*)5 小时前
Android 测试入门指南:ADB 基础配置与常用设备管理命令解析
android·adb
gxgldyh7 小时前
Android Framework源码解析(七):BootAnimation 启动流程解析——开机动画是如何显示出来的?
android
达达尼昂8 小时前
在 Claude Cowork 中用好 Claude Fable 5
android·人工智能·后端
sTone873758 小时前
写时复制COW的第一性理解
android·c++·flutter
sTone873758 小时前
Zygote的第一性理解
android
sTone873759 小时前
类RN框架通过Service暴露卡片渲染能力给AI Chat
android·react native
灯火不休9 小时前
Android Studio & Flutter 构建命令完全指南
android