android--如何将View转换成Bitmap

使用setDrawingCacheEnabled(boolean enabled);

/**
     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
     * null.</p>
     *
     * <p>Enabling the drawing cache is similar to
     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
     * acceleration is turned off. When hardware acceleration is turned on, enabling the
     * drawing cache has no effect on rendering because the system uses a different mechanism
     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
     * for information on how to enable software and hardware layers.</p>
     *
     * <p>This API can be used to manually generate
     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
     * {@link #getDrawingCache()}.</p>
     *
     * @param enabled true to enable the drawing cache, false otherwise
     *
     * @see #isDrawingCacheEnabled()
     * @see #getDrawingCache()
     * @see #buildDrawingCache()
     * @see #setLayerType(int, android.graphics.Paint)
     */
  • 启用或不启用绘图缓存;当启用时,下次调用getDrawingCache()或者buildDrawingCache()将会在bitmap上画出view。当不允许缓存时,调用draw(Canvas
    canvas)将不能根据缓存来画view。为了能够根据缓存来画view,你应该通过调用getDrawingCache()来请求绘图缓存,然后将它画在屏幕上,前提是返回的bitmap不为null。

  • 当硬件加速关掉时,启用绘图缓存和setLayerType(int,
    android.graphics.Paint)(设置一个层)相似。当硬件加速打开时,启用绘图缓存对渲染没有影响,因为系统使用了一个不同的机制来加速渲染,这个机制忽略了标志。如果你想给view使用bitmap,即使是硬件加速启用的情况下,可以查看{@link #setLayerType(int, android.graphics.Paint)}来获取更多关于如何启用软件、硬件层的信息。

  • 这个API可以被用于手动生成view的位图副本,通过设置标记为true,并且调用getDrawingCache()获取bitmap。

举个栗子:

View view = LayoutInflater.from(mContext).inflate(R.layout.test, null);
view.setDrawingCacheEnabled(true);
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap cacheBitmap = view.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值