這里的所有文本都應該可以通過編程方式編輯 - 換句話說,我想要一個可以通過編程方式編輯的模板,它可以保存為影像。
我還希望能夠設定影像的寬度(同時保持質量和縱橫比)。
我在 SO 上探索了許多類似問題的答案,但它們已過時/已棄用或不夠優雅,因此請不要將此問題標記為重復。我愿意使用來自 GitHub 的庫。
我嘗試將文本繪制到支持位圖的畫布上,但文本的位置因設備而異,這并不好。
uj5u.com熱心網友回復:
僅使用位圖就可以實作 100% 像素完美。您可以包含其他字體以強制它在所有設備型別上都相同。它將是獨立于任何平臺環境的圖片。
uj5u.com熱心網友回復:
在 TextView 上的 XML 檔案上使用以下方法
使用android:drawableTop引數
<TextView
android:id="@ id/textView20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@android:mipmap/sym_def_app_icon"
android:text="TextView"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />


您可以使用該.setText方法自動更改文本
uj5u.com熱心網友回復:
您想做的事情有一個技巧,請按照下列步驟操作:
- 為您要保存的影像創建一個 XML 布局,這將是您可編輯的輸出影像資料,例如:
注意:此方法中使用 View Binding,但是您可以使用其他方法訪問 XML 布局視圖
layout_data.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/custom_padding">
<ImageView
android:id="@ id/ivBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@ id/tvCenterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</layout>
- 在片段中訪問、編輯和保存布局的螢屏截圖:
private fun fillDataAndGetBitmap(image: Bitmap, title: String): Bitmap {
val layoutInflater: LayoutInflater = LayoutInflater.from(requireContext())
val layoutDataBinding = LayoutDatatBinding.inflate(layoutInflater, null, false)
// Fill in your image data into layout
layoutDataBinding.ivBackground.setImageBitmap(image)
layoutDataBinding.tvCenterText.text = title
// Get Bitmap of your layout
val outputBitmap = gettBitmapFromView(layoutDataBinding.root)
return outputBitmap
}
fun gettBitmapFromView(layout: View): Bitmap {
layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
layout.layout(0, 0, layout.measuredWidth, layout.measuredHeight)
val bitmap = Bitmap.createBitmap(layout.measuredWidth, layout.measuredHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
layout.layout(layout.left, layout.top, layout.right, layout.bottom)
layout.draw(canvas)
return bitmap
}
- Now you have a bitmap of your layout, you can share it via intent or save it to the user's device. Also, you can change the quality and aspect ratio of your bitmap, but that is out of the scope of this question, you can check Scaled Bitmap maintaining aspect ratio.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438914.html
下一篇:模板子類的集合
