gpt4 book ai didi

android - 如何在图像上绘制文本?

转载 作者:IT老高 更新时间:2023-10-28 22:19:19 25 4
gpt4 key购买 nike

我想在图像上绘制文本(用于将该图像与文本一起保存)。我有 ImageView 我将位图设置为我想在图像上绘制文本(用户输入的文本)的图像。我在保存之前试过这个.....

void saveImage() {
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();

} catch (Exception e) {
e.printStackTrace();
}
}

Xml 代码是..

<FrameLayout 
android:id="@+id/framelayout"
android:layout_marginTop="30dip"
android:layout_height="fill_parent"
android:layout_width="fill_parent">

<ImageView
android:id="@+id/ImageView01"
android:layout_alignParentTop="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>

<TextView android:id="@+id/text_view2"
android:layout_marginTop="20dip"
android:layout_width="wrap_content"
android:text="SampleText"
android:textSize="12pt"
android:layout_alignTop="@+id/ImageView01"
android:layout_height="wrap_content"/>

</FrameLayout>

最佳答案

作为 suggested by Vladislav Skoumal ,试试这个方法:

public Bitmap drawTextToBitmap(Context mContext,  int resourceId,  String mText) {
try {
Resources resources = mContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);

Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.rgb(110,110, 110));
// text size in pixels
paint.setTextSize((int) (12 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;

canvas.drawText(mText, x * scale, y * scale, paint);

return bitmap;
} catch (Exception e) {
// TODO: handle exception

return null;
}

}

调用这个方法

Bitmap bmp =drawTextToBitmap(this,R.drawable.aa,"Hello Android");
img.setImageBitmap(bmp);

输出

enter image description here

关于android - 如何在图像上绘制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com