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)
            }
        }
    }

}

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

相关推荐
Jerry20 小时前
Compose 设置文字样式
android
飞猿_SIR20 小时前
android定制系统完全解除应用安装限制
android
索迪迈科技21 小时前
影视APP源码 SK影视 安卓+苹果双端APP 反编译详细视频教程+源码
android·影视app源码·sk影视
孔丘闻言21 小时前
python调用mysql
android·python·mysql
萧雾宇1 天前
Android Compose打造仿现实逼真的烟花特效
android·flutter·kotlin
翻滚丷大头鱼1 天前
android 性能优化—ANR
android·性能优化
翻滚丷大头鱼1 天前
android 性能优化—内存泄漏,内存溢出OOM
android·性能优化
拜无忧1 天前
【教程】flutter常用知识点总结-针对小白
android·flutter·android studio
拜无忧1 天前
【教程】Flutter 高性能项目架构创建指南:从入门到高性能架构
android·flutter·android studio
用户2018792831671 天前
故事:公司的 "私人储物柜" 系统(ThreadLocalMap)
android·java