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
}
相关推荐
码农coding8 分钟前
android 12 中的VSYNC接收
android
GitLqr19 分钟前
Flutter 3.44 性能飞跃:深度解析 Android Platform View 的 HCPP 新特性
android·flutter·性能优化
码农coding24 分钟前
android 12 SurfaceFlinger中的CompositionEngine
android
Mem0rin2 小时前
[MySQL] 聚合函数、分组查询、连接查询
android·mysql
码龙-DragonCoding2 小时前
一键批量提取音频、提取视频
android·音视频·提取
祉猷并茂,雯华若锦2 小时前
Win下完美解决Allure报错,生成Web自动化测试报告
android·python·selenium·自动化
IT小盘4 小时前
08-FastAPI加MySQL实现AI对话记录持久化
android·mysql·fastapi
alice--小文子4 小时前
安卓(Android)- 怎么在adb中通过真机操作日志相关
android·adb
清泓y4 小时前
Android内存管理与性能优化面试真题
android·面试·性能优化
hopsky4 小时前
Wechatsync 安全审计报告
android·java·安全