我想将字符串中的文本转换为图像并将其显示在 ImageView
中,此外我想获取在运行时创建的图像的尺寸以供进一步使用。这是我通过搜索所做和使用的内容。
tv = new TextView(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60);
tv.setLayoutParams(layoutParams);
tv.setText("Some Text, can be long as much as required");
tv.setTextColor(Color.BLACK);
tv.setBackgroundColor(Color.WHITE);
Bitmap testB;
timer = new Timer();
timer.schedule(new TickerTask(), 1000,25);
testB = Bitmap.createBitmap(600, 20, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(testB);
tv.layout(0, 0, 380, 100);
tv.draw(c);
iv = (ImageView) findViewById(R.id.menuIcon);
iv.setLayoutParams(layoutParams);
iv.setBackgroundColor(Color.GREEN);
iv.setImageBitmap(testB);
问题: 参数未按照代码中的设置工作。 图像转换后不显示完整文本。
最佳答案
我认为它占据了整个屏幕,因为您没有诸如线性布局之类的容器,该容器随后包含具有布局约束的 ImageView,因此 ImageView 会扩展以填充可用屏幕。试试这个:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(80, 100);
tv.setLayoutParams(layoutParams);
tv.setText("testing 1 2 3");
tv.setTextColor(Color.BLACK);
tv.setBackgroundColor(Color.TRANSPARENT);
Bitmap testB;
testB = Bitmap.createBitmap(80, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(testB);
tv.layout(0, 0, 80, 100);
tv.draw(c);
ImageView iv = (ImageView)findViewById(R.id.menuIcon);
iv.setLayoutParams(layoutParams);
iv.setBackgroundColor(Color.GRAY);
iv.setImageBitmap(testB);
iv.setMaxHeight(80);
iv.setMaxWidth(80);
}
在你的 main.xml 文件中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/menuIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
关于安卓文字转图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545306/