下面列出了android.graphics.drawable.Drawable#createFromStream() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get the Drawable from URL
*
* @param urlString
* @return
*/
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
int scaledWidth = width;
int scaledHeight = height;
if (width > container.getMeasuredWidth()) {
scaledWidth = container.getMeasuredWidth();
scaledHeight = (int) (container.getMeasuredWidth() * height * 1.0f / width);
}
drawable.setBounds(0, 0, scaledWidth, scaledHeight);
drawable.setVisible(true, true);
return drawable;
} catch (Exception e) {
return null;
}
}
/**
* 微博文字转表情
*
* @param boundPx the icon' s rectangle bound, if zero, use the default
*/
public static SpannableString text2Emotion(Context context, String key, int boundPx) {
SpannableString spannable = new SpannableString(key);
InputStream inputStream = null;
Drawable drawable = null;
try {
inputStream = context.getAssets().open(TweetImageSpan.EMOTIONS_DIR + TweetImageSpan.EMOTIONS.get(key));
drawable = Drawable.createFromStream(inputStream, null);
} catch (IOException e) {
Log.e(TAG, "load emotion error!", e);
} finally {
closeIO(inputStream);
}
if (drawable != null) {
if (boundPx == 0) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
} else {
drawable.setBounds(0, 0, boundPx, boundPx);
}
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
spannable.setSpan(span, 0, key.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
return spannable;
}
private Drawable b(String str) {
Drawable createFromStream;
IOException e;
try {
InputStream open = getAssets().open(str);
createFromStream = Drawable.createFromStream(open, str);
try {
open.close();
} catch (IOException e2) {
e = e2;
e.printStackTrace();
return createFromStream;
}
} catch (IOException e3) {
IOException iOException = e3;
createFromStream = null;
e = iOException;
e.printStackTrace();
return createFromStream;
}
return createFromStream;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
}
String resaddr = data[position];
ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
Drawable d;
try {
d = Drawable.createFromStream(mContext.getAssets().open(resaddr), null);
imageView.setImageDrawable(d);
} catch (IOException e) {
Log.e("Adapter", e.getMessage(), e);
}
return convertView;
}
/***
* Get the Drawable from URL
* @param urlString
* @return
*/
public Drawable fetchDrawable(String urlString) {
InputStream is = null;
try {
is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
//设置图片的实际高低
drawable.setBounds(0, 0, 0 + MyApplication.width, 0
+ drawable.getIntrinsicHeight()* MyApplication.width / drawable.getIntrinsicWidth());
return drawable;
} catch (Exception e) {
if (is != null)
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the skill for the current row
ItemToSkillTree skill = mItemToSkillTreeCursor.getItemToSkillTree();
// Set up the text view
LinearLayout root = (LinearLayout) view.findViewById(R.id.listitem);
ImageView skillItemImageView = (ImageView) view.findViewById(R.id.item_image);
TextView skillItemTextView = (TextView) view.findViewById(R.id.item);
TextView skillAmtTextView = (TextView) view.findViewById(R.id.amt);
String nameText = skill.getItem().getName();
String amtText = "" + skill.getPoints();
skillItemTextView.setText(nameText);
skillAmtTextView.setText(amtText);
Drawable i = null;
String cellImage = "icons_items/" + skill.getItem().getFileLocation();
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
skillItemImageView.setImageDrawable(i);
root.setTag(skill.getItem().getId());
root.setOnClickListener(new DecorationClickListener(context, skill.getItem().getId()));
}
@Override
public Drawable getDrawable(String source) {
try {
InputStream inputStream = context.getAssets().open(source);
Drawable d = Drawable.createFromStream(inputStream, null);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
} catch (IOException e) {
// prevent a crash if the resource still can't be found
Log.e(HtmlTextView.TAG, "source could not be found: " + source);
return null;
}
}
/**
* 从Asset路径获取Drawable
*
* @param context
* @param filePath
* @return
*/
public static Drawable getAssetByPath(Context context, String filePath) {
Drawable drawable = WeakCache.getCache(TAG).get(filePath);
if (drawable == null) {
try {
if (context != null) {
drawable = Drawable.createFromStream(context.getAssets().open(filePath), null);
WeakCache.getCache(TAG).put(filePath, drawable);
}
} catch (Throwable e) {
}
}
return drawable;
}
Drawable loadImageForContact(String lookupKey) {
Uri contactUri = Contacts.lookupContact(mContext.getContentResolver(), Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey));
if (null == contactUri) {
return mDefaultDrawable;
}
InputStream contactImageStream = Contacts.openContactPhotoInputStream(mContext.getContentResolver(), contactUri);
if (contactImageStream != null) {
return Drawable.createFromStream(contactImageStream, "contact_image");
} else {
return mDefaultDrawable;
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the item for the current row
MonsterToArena monsterToArena = mMonsterToArenaCursor
.getMonsterToArena();
// Set up the text view
LinearLayout itemLayout = (LinearLayout) view
.findViewById(R.id.listitem);
ImageView monsterImageView = (ImageView) view
.findViewById(R.id.detail_monster_image);
TextView monsterTextView = (TextView) view
.findViewById(R.id.detail_monster_label);
String cellMonsterText = monsterToArena.getMonster().getName();
String cellTraitText = monsterToArena.getMonster().getTrait();
if (!cellTraitText.equals("")) {
cellMonsterText = cellMonsterText + " (" + cellTraitText + ")";
}
monsterTextView.setText(cellMonsterText);
Drawable i = null;
String cellImage = "icons_monster/"
+ monsterToArena.getMonster().getFileLocation();
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
monsterImageView.setImageDrawable(i);
itemLayout.setTag(monsterToArena.getMonster().getId());
}
/**
* 获得板块图标
*/
public static Drawable getForumlogo(Context contex, int fid) {
try {
InputStream ims = contex.getAssets().open("forumlogo/common_" + fid + "_icon.gif");
return Drawable.createFromStream(ims, null);
} catch (IOException ex) {
return null;
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Object result = ((MultiObjectCursor)cursor).getObject();
Class originalClass = result.getClass();
if (!mHandlers.containsKey(originalClass)) {
// Not expected, so marked as a runtime exception
throw new RuntimeException(
"Could not find handler for class " + originalClass.getName());
}
ResultHandler handler = mHandlers.get(originalClass);
ImageView imageView = (ImageView) view.findViewById(R.id.result_image);
TextView nameView = (TextView) view.findViewById(R.id.result_name);
TextView typeView = (TextView) view.findViewById(R.id.result_type);
String imagePath = handler.getImage(result);
if (imagePath != null) {
Drawable itemImage = null;
try {
itemImage = Drawable.createFromStream(
context.getAssets().open(imagePath), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageDrawable(itemImage);
}
nameView.setText(handler.getName(result));
typeView.setText(handler.getType(result));
view.setOnClickListener(handler.createListener(result));
}
@Override
public Drawable getDrawable(String source) {
Log.d("AssetImageGetter", "Get resource: " + source);
try {
// Load the resource from the assets/help/ directory.
InputStream sourceIS = resources.getAssets().open("help/" + source);
// Create a drawable from the stream
Drawable sourceDrawable = Drawable.createFromStream(sourceIS, "");
// This gives us the width of the display.
DisplayMetrics outMetrics = new DisplayMetrics();
FirstRunActivity.this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
// This tells us the ratio we have to work with.
double scale = (float)(outMetrics.widthPixels) / (float)(sourceDrawable.getIntrinsicWidth());
// Take up no more than 50% when in landscape, but 80% when in portrait.
double imscale = (outMetrics.widthPixels > outMetrics.heightPixels ? 0.5 : 0.8);
int width = (int)(imscale * outMetrics.widthPixels);
int height = (int)(imscale * scale * sourceDrawable.getMinimumHeight());
sourceDrawable.setBounds(0, 0, (int)(width), (int)(height));
return sourceDrawable;
} catch ( IOException e ) {
return getResources().getDrawable(R.drawable.error);
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the item for the current row
ArenaReward arenaReward = mArenaRewardCursor.getArenaReward();
// Set up the text view
LinearLayout itemLayout = (LinearLayout) view
.findViewById(R.id.listitem);
ImageView itemImageView = (ImageView) view
.findViewById(R.id.item_image);
TextView itemTextView = (TextView) view.findViewById(R.id.item);
TextView amountTextView = (TextView) view.findViewById(R.id.amount);
TextView percentageTextView = (TextView) view
.findViewById(R.id.percentage);
String cellItemText = arenaReward.getItem().getName();
int cellAmountText = arenaReward.getStackSize();
int cellPercentageText = arenaReward.getPercentage();
itemTextView.setText(cellItemText);
amountTextView.setText("" + cellAmountText);
String percent = "" + cellPercentageText + "%";
percentageTextView.setText(percent);
Drawable i = null;
String cellImage = "icons_items/" + arenaReward.getItem().getFileLocation();
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
itemImageView.setImageDrawable(i);
itemLayout.setTag(arenaReward.getItem().getId());
}
public static void exportPDF(Context ctx, Times times, @NonNull LocalDate from, @NonNull LocalDate to) throws IOException {
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo;
int pw = 595;
int ph = 842;
pageInfo = new PdfDocument.PageInfo.Builder(pw, ph, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Drawable launcher = Drawable.createFromStream(ctx.getAssets().open("pdf/launcher.png"), null);
Drawable qr = Drawable.createFromStream(ctx.getAssets().open("pdf/qrcode.png"), null);
Drawable badge =
Drawable.createFromStream(ctx.getAssets().open("pdf/badge_" + LocaleUtils.getLanguage("en", "de", "tr", "fr", "ar") + ".png"),
null);
launcher.setBounds(30, 30, 30 + 65, 30 + 65);
qr.setBounds(pw - 30 - 65, 30 + 65 + 5, pw - 30, 30 + 65 + 5 + 65);
int w = 100;
int h = w * badge.getIntrinsicHeight() / badge.getIntrinsicWidth();
badge.setBounds(pw - 30 - w, 30 + (60 / 2 - h / 2), pw - 30, 30 + (60 / 2 - h / 2) + h);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setARGB(255, 0, 0, 0);
paint.setTextSize(10);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("com.metinkale.prayer", pw - 30 - w / 2f, 30 + (60 / 2f - h / 2f) + h + 10, paint);
launcher.draw(canvas);
qr.draw(canvas);
badge.draw(canvas);
paint.setARGB(255, 61, 184, 230);
canvas.drawRect(30, 30 + 60, pw - 30, 30 + 60 + 5, paint);
if (times.getSource().drawableId != 0) {
Drawable source = ctx.getResources().getDrawable(times.getSource().drawableId);
h = 65;
w = h * source.getIntrinsicWidth() / source.getIntrinsicHeight();
source.setBounds(30, 30 + 65 + 5, 30 + w, 30 + 65 + 5 + h);
source.draw(canvas);
}
paint.setARGB(255, 0, 0, 0);
paint.setTextSize(40);
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(ctx.getText(R.string.appName).toString(), 30 + 65 + 5, 30 + 50, paint);
paint.setTextAlign(Paint.Align.CENTER);
paint.setFakeBoldText(true);
canvas.drawText(times.getName(), pw / 2.0f, 30 + 65 + 50, paint);
paint.setTextSize(12);
int y = 30 + 65 + 5 + 65 + 30;
int p = 30;
int cw = (pw - p - p) / 7;
canvas.drawText(ctx.getString(R.string.date), 30 + (0.5f * cw), y, paint);
canvas.drawText(FAJR.getString(), 30 + (1.5f * cw), y, paint);
canvas.drawText(Vakit.SUN.getString(), 30 + (2.5f * cw), y, paint);
canvas.drawText(Vakit.DHUHR.getString(), 30 + (3.5f * cw), y, paint);
canvas.drawText(Vakit.ASR.getString(), 30 + (4.5f * cw), y, paint);
canvas.drawText(Vakit.MAGHRIB.getString(), 30 + (5.5f * cw), y, paint);
canvas.drawText(Vakit.ISHAA.getString(), 30 + (6.5f * cw), y, paint);
paint.setFakeBoldText(false);
do {
y += 20;
canvas.drawText((from.toString("dd.MM.yyyy")), 30 + (0.5f * cw), y, paint);
canvas.drawText(times.getTime(from, FAJR.ordinal()).toLocalTime().toString(), 30 + (1.5f * cw), y, paint);
canvas.drawText(times.getTime(from, SUN.ordinal()).toLocalTime().toString(), 30 + (2.5f * cw), y, paint);
canvas.drawText(times.getTime(from, DHUHR.ordinal()).toLocalTime().toString(), 30 + (3.5f * cw), y, paint);
canvas.drawText(times.getTime(from, ASR.ordinal()).toLocalTime().toString(), 30 + (4.5f * cw), y, paint);
canvas.drawText(times.getTime(from, MAGHRIB.ordinal()).toLocalTime().toString(), 30 + (5.5f * cw), y, paint);
canvas.drawText(times.getTime(from, ISHAA.ordinal()).toLocalTime().toString(), 30 + (6.5f * cw), y, paint);
} while (!(from = from.plusDays(1)).isAfter(to));
document.finishPage(page);
File outputDir = ctx.getCacheDir();
if (!outputDir.exists())
outputDir.mkdirs();
File outputFile = new File(outputDir, times.getName().replace(" ", "_") + ".pdf");
if (outputFile.exists())
outputFile.delete();
FileOutputStream outputStream = new FileOutputStream(outputFile);
document.writeTo(outputStream);
document.close();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
Uri uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.FILE_PROVIDER_AUTHORITIES), outputFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
ctx.startActivity(Intent.createChooser(shareIntent, ctx.getResources().getText(R.string.export)));
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the combination for the current row
Combining item = mCombiningCursor.getCombining();
View v = view;
String item1 = item.getItem1().getName();
String item2 = item.getItem2().getName();
String item3 = item.getCreatedItem().getName();
String cellImage1 = "icons_items/" + item.getItem1().getFileLocation();
String cellImage2 = "icons_items/" + item.getItem2().getFileLocation();
String cellImage3 = "icons_items/" + item.getCreatedItem().getFileLocation();
int percent = item.getPercentage();
int min = item.getAmountMadeMin();
int max = item.getAmountMadeMax();
String temp = "" + min;
if (min != max){
temp = temp + "-" + max;
}
String percentage = "" + percent + "%";
TextView itemtv1 = (TextView) v.findViewById(R.id.item_text1);
TextView itemtv2 = (TextView) v.findViewById(R.id.item_text2);
TextView itemtv3 = (TextView) v.findViewById(R.id.item_text3);
ImageView itemiv1 = (ImageView) v.findViewById(R.id.item_img1);
ImageView itemiv2 = (ImageView) v.findViewById(R.id.item_img2);
ImageView itemiv3 = (ImageView) v.findViewById(R.id.item_img3);
LinearLayout itemlayout1 = (LinearLayout) v.findViewById(R.id.item1);
LinearLayout itemlayout2 = (LinearLayout) v.findViewById(R.id.item2);
RelativeLayout itemlayout3 = (RelativeLayout) v.findViewById(R.id.item3);
TextView percenttv = (TextView) v.findViewById(R.id.percentage);
TextView amttv = (TextView) v.findViewById(R.id.amt);
Drawable i1 = null;
Drawable i2 = null;
Drawable i3 = null;
try {
i1 = Drawable.createFromStream(context.getAssets()
.open(cellImage1), null);
i2 = Drawable.createFromStream(context.getAssets()
.open(cellImage2), null);
i3 = Drawable.createFromStream(context.getAssets()
.open(cellImage3), null);
} catch (IOException e) {
e.printStackTrace();
}
itemiv1.setImageDrawable(i1);
itemiv2.setImageDrawable(i2);
itemiv3.setImageDrawable(i3);
percenttv.setText(percentage);
amttv.setText(temp);
itemtv1.setText(item1);
itemtv2.setText(item2);
itemtv3.setText(item3);
itemlayout1.setOnClickListener(new ItemClickListener(context, item.getItem1().getId()));
itemlayout2.setOnClickListener(new ItemClickListener(context, item.getItem2().getId()));
itemlayout3.setOnClickListener(new ItemClickListener(context, item.getCreatedItem().getId()));
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the decoration for the current row
Decoration decoration = mDecorationCursor.getDecoration();
RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.listitem);
// Set up the text view
ImageView itemImageView = (ImageView) view.findViewById(R.id.item_image);
TextView decorationNameTextView = (TextView) view.findViewById(R.id.item);
TextView skill1TextView = (TextView) view.findViewById(R.id.skill1);
TextView skill1amtTextView = (TextView) view.findViewById(R.id.skill1_amt);
TextView skill2TextView = (TextView) view.findViewById(R.id.skill2);
TextView skill2amtTextView = (TextView) view.findViewById(R.id.skill2_amt);
String decorationNameText = decoration.getName();
String skill1Text = decoration.getSkill1Name();
String skill1amtText = "" + decoration.getSkill1Point();
String skill2Text = decoration.getSkill2Name();
String skill2amtText = "";
if (decoration.getSkill2Point() != 0) {
skill2amtText = skill2amtText + decoration.getSkill2Point();
}
Drawable i = null;
String cellImage = "icons_items/" + decoration.getFileLocation();
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
itemImageView.setImageDrawable(i);
decorationNameTextView.setText(decorationNameText);
skill1TextView.setText(skill1Text);
skill1amtTextView.setText(skill1amtText);
skill2TextView.setVisibility(View.GONE);
skill2amtTextView.setVisibility(View.GONE);
if (!skill2amtText.equals("")) {
skill2TextView.setText(skill2Text);
skill2amtTextView.setText(skill2amtText);
skill2TextView.setVisibility(View.VISIBLE);
skill2amtTextView.setVisibility(View.VISIBLE);
}
itemLayout.setTag(decoration.getId());
if (fromAsb) {
boolean fitsInArmor = (decoration.getNumSlots() <= maxSlots);
view.setEnabled(fitsInArmor);
// Set the jewel image to be translucent if disabled
// TODO: If a way to use alpha with style selectors exist, use that instead
itemImageView.setAlpha((fitsInArmor) ? 1.0f : 0.5f);
if (fitsInArmor) {
itemLayout.setOnClickListener(new DecorationClickListener(context, decoration.getId(), true, activity));
}
}
else {
itemLayout.setOnClickListener(new DecorationClickListener(context, decoration.getId()));
}
}
/**
* 获取用户头像
*
* @param dir 可null。非空则将头像输出在文件中
* @param pref 可null。非空,且需要更新头像则将头像唯一标识更新在配置文件中
* @return Drawable 头像。如操作成功返回新的头像Drawable。否则返回null
*/
public Drawable getAvatar(File dir, SharedPreferences pref) {
try {
VCard card = getVCard();
//如果无法下载名片或者没有头像则返回null
if (card == null || card.getAvatar() == null) {
return null;
}
//如果有配置,没有必要更新则不更新
if (pref != null) {
if (card.getField(AVATAG).equals(pref.getString(AVATAG, ""))) {
if(dir != null && dir.exists())
return null;
}
}
//如有dir,更新文件
if(dir != null){
FileOutputStream out = new FileOutputStream(dir);
Bitmap image = BitmapFactory.decodeByteArray(
card.getAvatar(), 0, card.getAvatar().length);
//压缩成功则输出,失败返回null
if(image.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
else {
return null;
}
}
//如有配置,更新配置
if(pref != null){
pref.edit().putString(AVATAG, card.getField(AVATAG)).apply();
}
return Drawable.createFromStream(new ByteArrayInputStream(card.getAvatar()), null);
} catch (IOException e) {
return null;
}
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the item for the current row
MonsterToQuest monsterToQuest = mMonsterToQuestCursor
.getMonsterToQuest();
// Set up the text view
LinearLayout itemLayout = (LinearLayout) view
.findViewById(R.id.listitem);
ImageView monsterImageView = (ImageView) view
.findViewById(R.id.detail_monster_image);
TextView monsterTextView = (TextView) view
.findViewById(R.id.detail_monster_label);
TextView unstableTextView = (TextView) view
.findViewById(R.id.detail_monster_unstable);
String cellMonsterText = monsterToQuest.getMonster().getName();
String cellTraitText = monsterToQuest.getMonster().getTrait();
String cellUnstableText = monsterToQuest.getUnstable();
if (!cellTraitText.equals("")) {
cellMonsterText = cellMonsterText + " (" + cellTraitText + ")";
}
if (cellUnstableText.equals("no")) {
cellUnstableText = "";
}
else {
cellUnstableText = "Unstable";
}
monsterTextView.setText(cellMonsterText);
unstableTextView.setText(cellUnstableText);
Drawable i = null;
String cellImage = "icons_monster/"
+ monsterToQuest.getMonster().getFileLocation();
try {
i = Drawable.createFromStream(
context.getAssets().open(cellImage), null);
} catch (IOException e) {
e.printStackTrace();
}
monsterImageView.setImageDrawable(i);
itemLayout.setTag(monsterToQuest.getMonster().getId());
itemLayout.setOnClickListener(new MonsterClickListener(context,
monsterToQuest.getMonster().getId()));
}
/**
* get drawable by imageUrl
*
* @param imageUrl
* @param readTimeOutMillis read time out, if less than 0, not set, in mills
* @param requestProperties http request properties
* @return
*/
public static Drawable getDrawableFromUrl(String imageUrl, int readTimeOutMillis,
Map<String, String> requestProperties) {
InputStream stream = getInputStreamFromUrl(imageUrl, readTimeOutMillis, requestProperties);
Drawable d = Drawable.createFromStream(stream, "src");
closeInputStream(stream);
return d;
}