如何将textview转换为精确大小的图像,如屏幕截图
问题描述:
我是新的android开发人员,我试图将文本视图转换或截图成图像,最近我发现了这个问题的代码片段代码,它可以正常工作当文本非常小时,就像一行一行,文本大小一样的文本,但如果文本大小超过一行或文本大小较大,则文本会以一行压缩文本,文本的大小变得非常小。 这里是java代码。如何将textview转换为精确大小的图像,如屏幕截图
public class MainActivity extends AppCompatActivity {
ImageView bmImage;
TextView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (TextView) findViewById(R.id.screen);
bmImage = (ImageView)findViewById(R.id.image);
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(true);
Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
bmImage.setImageBitmap(b);
bmImage.setBackgroundColor(Color.GRAY);
}}
这里是xml代码。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.jarad.c_to_i.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/screen"
android:textSize="20dp"
android:text="My name is Mo7mdech I am 30 years old, please help my in this problemَ"
/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
请帮忙,谢谢。
答
您可以尝试手动将相同的文本绘制到新的Canvas中。您可以通过TextView.getTextPaint()
获得textPaint。
答
我发现我做错了什么.. 我做了宽度 - > match_parent和高度 - > wrap_content的文本,我认为这不是给我的图像中的文本的确切大小,我不知道究竟为什么(我认为宽度没有固定数字的问题),但我最近做的是给文本一个固定的宽度,图像开始给我相同的文本宽度,所以我改变了图像高度 - > wrap_content和它开始给我一个文本的副本作为截图,这就是我现在想要的。 我知道这不是一个完美的解决方案,特别是宽度小于我放入文本的任何设备,但它给了我直到现在我想要的。
如果有人有更好的答案请不要犹豫,回复。
这是我的新代码..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/screen"
android:padding="6dp"
tools:context="com.jarad.c_to_i.MainActivity">
<TextView
android:layout_width="370dp"
android:layout_height="wrap_content"
android:id="@+id/text"
android:textSize="20dp"
android:text="My name is Mo7mdech I am 30 years old, please help my in this problem"
/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
保存屏幕比作物借你的TextView的坐标的形象?我知道它不是答案,但我相信这会起作用 –
我想过它,但我想通过我的代码来解决它,因为我确信我错过了某些东西。 – Mo7mdech