【发布时间】:2018-01-31 06:01:57
【问题描述】:
目前我正在制作一个照片编辑器应用程序。我有活动,您可以在其中向图像添加文本。我需要在位图中保存带有文本的图像。我已经尝试保存绘图缓存,但问题是它保存的图像质量很差。原始图像 4032*3024 保存时使用的图像视图大小为 1517 * 1137。我尝试将位图缩放到原始大小,但质量太差。现在我正在尝试在画布上绘制原始位图,然后在与视图相同的位置上绘制文本。
float x = editText.getLeft() * (scale);
float y = editText.getTop() * (scale);
canvas.drawText(editText.getText().toString(), x, y, tp);
但由于某种原因,文本不在同一个地方。我尝试使用密度来获取坐标,但它也不起作用。
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/add_text_color_picker_relative_layout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<RelativeLayout
android:id="@+id/edit_photo_add_text_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/edit_photo_add_text_main_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
<EditText
android:id="@+id/edit_photo_add_text_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rect_edittext"
android:hint="Поле для текста"
android:inputType="textNoSuggestions"
android:padding="4dp"
android:textSize="14dp" />
</RelativeLayout>
</RelativeLayout>
这里是java代码:
public Bitmap createImage(View view, int imageViewId, int textViewId, Context context){
ImageView imageView = (ImageView) view.findViewById(imageViewId);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
float bitmapRatio = (bitmap.getWidth()) / bitmap.getHeight();
float imageViewRatio = (imageView.getWidth()) / imageView.getHeight();
float scaleW = bitmap.getWidth() / imageView.getWidth();
float scaleH = bitmap.getHeight() / imageView.getHeight();
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
bitmap = bitmap.copy(bitmapConfig, true);
EditText editText = (EditText) view.findViewById(textViewId);
float density = context.getResources().getDisplayMetrics().density;
Canvas canvas = new Canvas(bitmap);
canvas.setBitmap(bitmap);
TextPaint tp = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
tp.setColor(Color.WHITE);
tp.setTextSize(editText.getTextSize()*density);
Resources resources = context.getResources();
float scale = resources.getDisplayMetrics().density;
int[] xy = {0, 0};
editText.getLocationOnScreen(xy);
float x = xy[0] * (scaleW);
float y = xy[1] * (scaleH);
canvas.drawText(editText.getText().toString(), x, y, tp);
canvas.save();
canvas.restore();
return bitmap; }
【问题讨论】:
标签: android image canvas bitmap