关键Java代码
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import android.widget.LinearLayout;
import android.text.TextUtils;
public class IconGeneratorActivity extends Activity {
private static final String TAG = "IconGeneratorActivity";
private LinearLayout parentLayout;
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_icon);
parentLayout = findViewById(R.id.parentLayout);
String[] localeNames = getAssets().getLocales();
Arrays.sort(localeNames);
ArrayList<Locale> locales = new ArrayList<Locale>();
for (String ln : localeNames) {
int u = ln.indexOf('-');
if (u >= 0) {
Log.e(TAG, "locale = " + ln);
locales.add(new Locale(ln.substring(0, u), ln.substring(u+1)));
}
}
final String[] modes = new String[] {"abc", "Abc", "ABC"};
for (final String localeName : localeNames) {
if (!TextUtils.isEmpty(localeName)) {
for (final String mode : modes) {
String textLocale = localeName;
if (modes[0].equals(mode)) {
} else if (modes[1].equals(mode)) {
textLocale = textLocale.substring(0,1).toUpperCase() + textLocale.substring(1);
} else if (modes[2].equals(mode)) {
textLocale = textLocale.toUpperCase();
}
final TextView tv_locale = new TextView(this);
parentLayout.addView(tv_locale, -2, -2);
tv_locale.setText(textLocale);
tv_locale.setDrawingCacheEnabled(true);
tv_locale.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
tv_locale.setPadding(0, 0, 0, 0);
tv_locale.setTextColor(android.graphics.Color.parseColor("#ffffff"));
tv_locale.setTextSize(20);
tv_locale.setIncludeFontPadding(false);
tv_locale.postDelayed(new Runnable(){
public void run() {
if (tv_locale != null && tv_locale.getDrawingCache() != null) {
int modeNum = 0;
if (modes[0].equals(mode)) {
modeNum = 0;
} else if (modes[1].equals(mode)) {
modeNum = 1;
} else if (modes[2].equals(mode)) {
modeNum = 2;
}
saveBitmap(tv_locale.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false), "ic_locale_"+localeName.replaceAll("-","_").toLowerCase()+"_" + modeNum + ".png");
}
}
}, 300);
}
}
}
}
private void saveBitmap(Bitmap b, String filename) {
try {
File pngFolder = new File("/sdcard/pngs/");
if (!pngFolder.exists()) {
pngFolder.mkdirs();
}
FileOutputStream fos = new FileOutputStream(new File("/sdcard/pngs/" + filename));
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (IOException e) {
Log.i(TAG, "failed to write PNG", e);
}
}
}
给 TextView 加边框
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00000000"/>
<stroke android:width="2dip" android:color="#ff000000" />
</shape>
运行了之后把 /sdcard/pngs/ 下的图片全都pull出来就可以使用了,此方法可以自己生成一些简单的图片,不再需要找UI做图