[英]how to convert textview into image with exact size like screenshot
我是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>
請幫助,謝謝。
您可以嘗試將相同的文本手動繪制到新的“畫布”中。 您可以通過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"
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.