使用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);