Android 通过View生成Bitmap

Android 通过View生成Bitmap

复制代码
fun getBitmapByView(view: View?): Bitmap? {
    if (null == view) {
        return null
    }
    var bitmap: Bitmap? = null

    // 步骤一:获取视图的宽和高
    val width: Int = view.getRight() - view.getLeft()
    val height: Int = view.getBottom() - view.getTop()

    // 判断背景是否为不透明
    val opaque = view.getDrawingCacheBackgroundColor() !== 0 || view.isOpaque()
    val quality: Bitmap.Config
    quality = if (!opaque) {
        when (view.getDrawingCacheQuality()) {
            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH -> Bitmap.Config.ARGB_8888
            else -> Bitmap.Config.ARGB_8888
        }
    } else {
        Bitmap.Config.RGB_565
    }

    // 步骤二:生成bitmap
    bitmap = Bitmap.createBitmap(resources.displayMetrics, width, height, quality)
    bitmap.density = resources.displayMetrics.densityDpi
    if (opaque) {
        bitmap.setHasAlpha(false)
    }
    val clear = view.getDrawingCacheBackgroundColor() !== 0

    // 步骤三:绘制canvas
    val canvas = Canvas(bitmap)
    if (clear) {
        bitmap.eraseColor(view.getDrawingCacheBackgroundColor())
    }
    view.computeScroll()
    val restoreCount: Int = canvas.save()
    canvas.translate((-view.getScrollX()).toFloat(), (-view.getScrollY()).toFloat())
    view.draw(canvas)
    canvas.restoreToCount(restoreCount)
    canvas.setBitmap(null)
    return bitmap
}
相关推荐
Digitally8 小时前
如何将安卓手机备份到电脑?7种方法
android
火柴就是我9 小时前
android:enableJetifier=true 再学习
android·flutter
杨筱毅9 小时前
【Android】【底层原理】深入解析SELinux模块
android·底层机制
Tom4i9 小时前
基于 Launcher3 的 iOS 风格桌面 04 拖拽和移位
android
2501_915106329 小时前
iOS 反编译防护工具与实战组合 从静态侦察到 IPA 成品加固的工程化路径
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者813 小时前
iOS 26 iPhone 使用记录分析 多工具组合构建全方位设备行为洞察体系
android·ios·小程序·uni-app·cocoa·iphone·webview
zhangphil20 小时前
HARDWARE 属性的Bitmap与普通Bitmap,GPU与RenderThread渲染与处理方式异同比较,Android
android
消失的旧时光-194321 小时前
Flutter 异步编程:Future 与 Stream 深度解析
android·前端·flutter
alexhilton1 天前
Compose CameraX现已稳定:给Composer的端到端指南
android·kotlin·android jetpack
阿里云云原生1 天前
移动端性能监控探索:可观测 Android 采集探针架构与实现
android