如何将textview转换为具有精确尺寸的图像,如截图

时间:2017-10-17 05:10:52

标签: java android image android-layout

我是Android开发的新手,我正在尝试将文本视图转换或截图为图像,最近我找到了这个问题的代码片段,当文本非常小,就像一句话一样,它可以正常工作行和小文本大小,但如果有多行或大文本大小,它会使图像的文本压缩成一行,文本的大小变得非常小。 这是java代码。

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>

请帮助,谢谢。

2 个答案:

答案 0 :(得分:0)

您可以尝试手动将相同的文本绘制到新的画布中。您可以通过TextView.getTextPaint()获取textPaint。

答案 1 :(得分:0)

我发现我做错了什么.. 我用宽度制作了文字 - &gt; match_parent和高度 - &gt; wrap_content,我认为这不是给我一个图像中文本的确切大小我不知道为什么(我认为宽度没有固定数字的问题)但我最近做的是给文本一个固定的宽度和图像开始给我相同的文本宽度,所以我将图像高度更改为 - &gt; 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"
    />