
如何使用GlIDe库将Bitmap加载到我的ImageVIEw中?
我想用文本创建自定义图像,并使用GlIDe将其加载到imagevIEw中.
这是我用文本创建自定义位图的方法
public Bitmap imageWithText(String text) { TextVIEw tv = new TextVIEw(context); tv.setText(text); tv.setTextcolor(color.WHITE); tv.setBackgroundcolor(color.BLACK); tv.setTypeface(null, Typeface.BolD); tv.setGravity(Gravity.CENTER); tv.setTextSize(20); tv.setpadding(0, 25, 0, 0); Bitmap testB = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(testB); tv.layout(0, 0, 100, 100); tv.draw(c); return testB;}但是,当我尝试使用滑动加载此位图时,我收到错误
GlIDe.with(getContext()).load(imageWithText("Random text")).into(holder.imgPhoto);解决方法:
@rookiedev is right, there’s no load(Bitmap) in Glide,原因是:获取位图通常需要时间,有时会阻塞I / O.因此,在UI线程上调用imageWithText并不是一个好习惯.更新:据说我一段时间提出了this feature;虽然黑客更容易做,你可以在下面找到“滑行方式”,我强烈推荐.
GlIDe的设计灵活,这个问题表明这种特性非常好.以下实现可能看起来很长,但所有部分都有其存在的理由.鉴于性能提升,适合您的生成器进入GlIDe世界的代码数量并不多.我试图将其格式化为简短,折叠不相关的部分并使用静态导入更短(请参阅导入的结尾).
该代码还包括以编程方式生成的UI,因此您只需将以下所有代码复制粘贴到GlIDeGeneratedImageListFragment.java中并运行它;唯一的外部依赖是支持lib的RecyclerVIEw.
class GeneratingAdapter extends RecyclerVIEw.Adapter<RecyclerVIEw.VIEwHolder> { // See https://docs.Google.com/drawings/d/1KyOJkNd5Dlm8_awZpftzW7KtqgNR6GURvuF6RfB210g/edit?usp=sharing // ModelType/A, DataType/T, ResourceType/Z, TranscodeType/R private final GenericRequestBuilder<GenerateParams, GenerateParams, Bitmap, GlIDeDrawable> generator; public GeneratingAdapter(final Context context) { generator = GlIDe // this part should be cleaner in GlIDe 4.0, but that's not released yet .with(context) .using(new GenerateParamsPassthroughModelLoader(), GenerateParams.class) // custom class .from(GenerateParams.class) .as(Bitmap.class) .transcode(new BitmapToGlIDeDrawableTranscoder(context), GlIDeDrawable.class) // builtin .decoder(new GenerateParamsBitmapResourceDecoder(context)) // custom class .encoder(new BitmapEncoder(Bitmap.CompressFormat.PNG, 0/*ignored for lossless*/)) // builtin .cacheDecoder(new fileToStreamDecoder<Bitmap>(new StreamBitmapDecoder(context))) // builtin //.placeholder(new colorDrawable(color.YELLOW)) // you can pre-set placeholder and error .error(new colorDrawable(color.RED)) // so it's easIEr when binding //.diskCacheStrategy(diskCacheStrategy.NONE) // only for deBUGging to always regenerate //.skipMemoryCache(true) // only for deBUGging to always regenerate ; } @OverrIDe public int getItemCount() { return 1000; } private final float[] colorCache = new float[] {0, 1.0f, 0.5f}; private final float[] bgCache = new float[] {0, 0.5f, 1.0f}; @OverrIDe public voID onBindVIEwHolder(RecyclerVIEw.VIEwHolder holder, int position) { colorCache[0] = bgCache[0] = (position * 15) % 360; // just to have a fancy example :) GenerateParams params = new GenerateParams( // omit position to see GlIDe caching in action (every 24th item / 12th row is the same) "androID text"/* + " #" + position*/, color.HSVTocolor(colorCache), color.HSVTocolor(bgCache) ); generator/*.clone() in case you see weird behavior*/.load(params).into((ImageVIEw)holder.itemVIEw); } @OverrIDe public RecyclerVIEw.VIEwHolder onCreateVIEwHolder(VIEwGroup parent, int vIEwType) { int height = parent.getContext().getResources().getdisplayMetrics().heightPixels / 3; ImageVIEw vIEw = new ImageVIEw(parent.getContext()); vIEw.setLayoutParams(new RecyclerVIEw.LayoutParams(MATCH_PARENT, height)); vIEw.setScaleType(ImageVIEw.ScaleType.FIT_CENTER); return new RecyclerVIEw.VIEwHolder(vIEw) {}; // anon class for brevity }}public class GlIDeGeneratedImageListFragment extends Fragment { @OverrIDe public @Nullable VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container, Bundle savedInstanceState) { RecyclerVIEw vIEw = new RecyclerVIEw(container.getContext()); vIEw.setLayoutParams(new marginLayoutParams(MATCH_PARENT, MATCH_PARENT)); vIEw.setLayoutManager(new GrIDLayoutManager(container.getContext(), 2 /*columns*/)); vIEw.setAdapter(new GeneratingAdapter(vIEw.getContext())); return vIEw; }}/** Extracted params from imageWithText, but left some hardcoded values like 20sp/bold/center in {@link Generators}. */class GenerateParams { final String text; final int color; final int background; public GenerateParams(String text, int color, int bg) { this.text = text; this.color = color; this.background = bg; } public String getID() { // Todo make sure it's unique for every possible instance of GenerateParams // because it will affect how the resulting bitmap is cached // the below is correct correct for the current fIElds, if those change this has to change return String.format(Locale.ROOT, "%s-%08x-%08x", text, color, background); }}/** Boilerplate because of the degeneration in ModelType == DataType, but important for caching. * @see GeneratingAdapter#generator */class GenerateParamsPassthroughModelLoader implements ModelLoader<GenerateParams, GenerateParams> { @OverrIDe public DataFetcher<GenerateParams> getResourceFetcher(final GenerateParams model, int wIDth, int height) { return new DataFetcher<GenerateParams>() { @OverrIDe public GenerateParams loadData(Priority priority) throws Exception { return model; } @OverrIDe public voID cleanup() { } @OverrIDe public String getID() { return model.getID(); } @OverrIDe public voID cancel() { } }; }}/** Handles pooling to reduce/prevent GC lagging from too many {@link Bitmap#createBitmap}s */class GenerateParamsBitmapResourceDecoder implements ResourceDecoder<GenerateParams, Bitmap> { private final Context context; public GenerateParamsBitmapResourceDecoder(Context context) { this.context = context; } @OverrIDe public Resource<Bitmap> decode(GenerateParams source, int wIDth, int height) throws IOException { BitmapPool pool = GlIDe.get(context).getBitmapPool(); Bitmap bitmap = pool.getDirty(wIDth, height, Bitmap.Config.ARGB_8888); if (bitmap == null) { bitmap = Bitmap.createBitmap(wIDth, height, Bitmap.Config.ARGB_8888); } Generators.imageWithTextNolayout(context, bitmap, source); return BitmapResource.obtain(bitmap, pool); } @OverrIDe public String getID() { // be careful if you change the Generator implementation you have to change this // otherwise the users may see a cached image; or clear cache on app update return "com.example.MyImageGenerator"; }}class Generators { /** OP's original implementation fixed for real centering */ public static Bitmap imageWithText(Context context, Bitmap bitmap, GenerateParams params) { TextVIEw vIEw = new TextVIEw(context); vIEw.setText(params.text); vIEw.setTextcolor(params.color); vIEw.setBackgroundcolor(params.background); vIEw.setTypeface(null, Typeface.BolD); vIEw.setGravity(Gravity.CENTER); vIEw.setTextSize(20 /*sP*/); Canvas canvas = new Canvas(bitmap); vIEw.measure(makeMeasureSpec(canvas.getWIDth(), EXACTLY), makeMeasureSpec(canvas.getHeight(), EXACTLY)); vIEw.layout(0, 0, canvas.getWIDth(), canvas.getHeight()); vIEw.draw(canvas); return bitmap; } /** Generate centered text without creating a VIEw, more lightweight. * ConsIDer https://stackoverflow.com/a/8369690/253468 for multiline support. */ public static Bitmap imageWithTextNolayout(Context context, Bitmap bitmap, GenerateParams params) { Paint paint = new Paint(); paint.setcolor(params.color); paint.setTextAlign(Paint.Align.CENTER); // text's anchor for the x given in drawText paint.setTextSize(applyDimension(COMPLEX_UNIT_SP, 20, context.getResources().getdisplayMetrics())); paint.setTypeface(Typeface.DEFAulT_BolD); Canvas canvas = new Canvas(bitmap); canvas.drawcolor(params.background); canvas.drawText(params.text, canvas.getWIDth() / 2, canvas.getHeight() / 2, paint); return bitmap; }}// Here are the imports in case you need it;// dIDn't want to put it in the beginning to keep the relevant code first.import java.io.IOException;import java.util.Locale;import androID.content.Context;import androID.graphics.*;import androID.graphics.drawable.colorDrawable;import androID.os.Bundle;import androID.support.annotation.Nullable;import androID.support.v4.app.Fragment;import androID.support.v7.Widget.*;import androID.vIEw.*;import androID.vIEw.VIEwGroup.marginLayoutParams;import androID.Widget.*;import static androID.util.TypedValue.*;import static androID.vIEw.VIEw.MeasureSpec.*;import static androID.vIEw.VIEwGroup.LayoutParams.*;import com.bumptech.glIDe.*;import com.bumptech.glIDe.load.ResourceDecoder;import com.bumptech.glIDe.load.data.DataFetcher;import com.bumptech.glIDe.load.engine.Resource;import com.bumptech.glIDe.load.engine.bitmap_recycle.BitmapPool;import com.bumptech.glIDe.load.model.ModelLoader;import com.bumptech.glIDe.load.resource.bitmap.*;import com.bumptech.glIDe.load.resource.drawable.GlIDeDrawable;import com.bumptech.glIDe.load.resource.file.fileToStreamDecoder;import com.bumptech.glIDe.load.resource.transcode.BitmapToGlIDeDrawableTranscoder;这是它的样子(实际滚动更顺畅,GIF真的很低FPS):
注意它如何加载前几个项目然后逐渐加载其余项目.内存缓存和池预热需要一点点,但如果你想要更平滑的显示,你可以使用预加载器.它热身后滚动得很好. *** 作栏上的删除按钮调用GlIDe.cleardiskCache()和GlIDe.clearMemory(),以便它再次开始重新生成项目.
总结以上是内存溢出为你收集整理的java – 使用Glide将位图加载到ImageView中全部内容,希望文章能够帮你解决java – 使用Glide将位图加载到ImageView中所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)