gpt4 book ai didi

Android:在不绘制的情况下生成 View 的位图

转载 作者:太空狗 更新时间:2023-10-29 15:42:10 27 4
gpt4 key购买 nike

我们在从特定 View 生成位图时遇到了问题。限制是它不能渲染 View (绘图)。有没有人有任何提示如何解决这个问题?

类 View 的文档 (http://developer.android.com/reference/android/view/View.html) 对 Android 用于呈现 View 的步骤进行了一些解释。在这种情况下,我们将在“布局”步骤中进行操作,而不是在“绘图”操作中进行操作。任何有想法的人都可以举个例子吗?

我的代码生成异常:错误 -> 宽度和高度必须> 0

...
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = null;
try {
b = Bitmap.createBitmap(
v.getWidth(),
v.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.measure(v.getWidth(), v.getHeight());
v.layout(0, 0, v.getWidth(), v.getHeight());
v.draw(c);

} catch (Exception e) {

Log.e(MainActivity.TAG, "error -> "+e.getMessage());
}



return b;
}


public void snap(View v) {


LayoutInflater inflate = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = new View(getBaseContext());
view = inflate.inflate(R.layout.list_item, null);


Log.d(MainActivity.TAG, "getWidth -> "+view.getWidth());
Log.d(MainActivity.TAG, "getHeight -> "+view.getHeight());

Bitmap b = loadBitmapFromView(view);
if (b != null) {

LinearLayout mainLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
ImageView image = new ImageView(this);
image.setImageBitmap(b);

mainLayout.addView(image);
}


}

最佳答案

我是这样找到解决方案的:

public static Bitmap getScreenViewBitmap(final View v) {
v.setDrawingCacheEnabled(true);

v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false); // clear drawing cache

return b;
}

关于Android:在不绘制的情况下生成 View 的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16598349/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com