我正在尝试通过一个字符串数组生成图像,方法是通过绘画画布将字符串文本转换为位图,并且在一个活动中生成50张图像。
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
Bitmap copy;
DisplayMetrics displayMetrics = new DisplayMetrics ();
getWindowManager ().getDefaultDisplay ().getMetrics (displayMetrics);
int width = displayMetrics.widthPixels;
String text = listArray[position];
text.replace("\'", "");
text.replace("\"", "");
Bitmap icon = BitmapFactory.decodeResource (mContext.getResources (), R.drawable.abraham);
TextPaint paint = new TextPaint ();
paint.setColor (Color.parseColor ("#000000"));
paint.setTextSize ((width / 10) - (text.length () / 6));
paint.setTypeface (Typeface.create (Typeface.createFromAsset (mContext.getAssets (), "fonts/underwood_champion.ttf"), Typeface.BOLD));
copy = icon.copy (Bitmap.Config.RGB_565, true);
Canvas canvas = new Canvas (copy);
StaticLayout layout = new StaticLayout (text, paint, canvas.getWidth () - 100, Layout.Alignment.ALIGN_CENTER, 1.3f, 3, false);
canvas.translate (100, (width / 2)+30);//(canvas.getHeight()/2)-(text.length ())); //position the text
layout.draw (canvas);
int size = width / 2;
imageView = new ImageView (mContext);
imageView.setLayoutParams (new GridView.LayoutParams (size, size));
imageView.setScaleType (ImageView.ScaleType.CENTER_CROP);
imageView.setPadding (30, 30, 30, 30);
imageView.setImageBitmap (copy);
return imageView;
}
我遇到了例外情况:
Process: com.ahsaashafeez.textoverbitmap, PID: 7957
java.lang.OutOfMemoryError: Failed to allocate a 7144212 byte allocation with 4194304 free bytes and 4MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.Bitmap.nativeCopy(Native Method)
at android.graphics.Bitmap.copy(Bitmap.java:592)
at com.ahsaashafeez.textoverbitmap.MainActivity$ImageAdapter.getView(MainActivity.java:84)
at android.widget.AbsListView.obtainView(AbsListView.java:2362)
at android.widget.GridView.makeAndAddView(GridView.java:1439)
在MainActivity行中:
copy = icon.copy (Bitmap.Config.RGB_565, true);
注意:我已经完成了该步骤。
<application
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">