Glide使用中遇到的问题及解决

动态添加  Imageview 使用glide 进行对图片的操作,保证了图片的不变形  而且高度自动比例调控

如果wrap_content的高度,则ImageView的高度会为原图片的像素值高度

故做以下处理:    屏幕宽度减去的 20 dp  为 llPicContiner 的 内左边距+内右边距

for (int i = 0; i < dataBean.getPath().size(); i++) {
    final ImageView imageView = new ImageView(mContext);
    final LinearLayout.LayoutParams  layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.bottomMargin = UiUtils.dp2px(mContext,6);
    //   imageView.setLayoutParams(layoutParams);
    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    Glide.with(mContext).load(NetPath.BaseDNS_Url+dataBean.getPath().get(i))
            .listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    if (resource.getIntrinsicHeight() == resource.getIntrinsicWidth()){
                        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT ;
                    }else {
                        float scale = (float) resource.getIntrinsicWidth() / (float) (UiUtils.getPhoneWidth(mContext) - UiUtils.dp2px(mContext,20) );
                        if (scale > 1){
                            int vh = Math.round((float)resource.getIntrinsicHeight() / scale);
                            layoutParams.height = vh ;
                        }else {
                            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT ;
                        }
                    }
                    imageView.setLayoutParams(layoutParams);
                    return false;
                }
            })
            .into(imageView);
    llpicContiner.addView(imageView);
}


Glide的清除缓存:

                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        Glide.get(mContext).clearDiskCache();   // 必须在子线程中执行
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Glide.get(mContext).clearMemory();    // 必须在主线程中执行
                                Glide.with(mContext).load(FaceUtil.getImagePath(mContext))
                                        .skipMemoryCache(true)
                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                                        .transform(new GlideCircleTransform(mContext))
                                        .into(pic2);
                            }
                        });
                    }
                }).start();
使用场景:  在本地裁剪图片后 保存的图片路径是唯一的   而图片会根据每次的裁剪变化  保存的图片的路径和文件名是不变的

使用了  clearDiskCache和  clearMemory 都不行

然后就改成了   让其  跳过内存缓存   磁盘缓存策略设置为NONE  就是不缓存到磁盘

解决了问题。

/**
 * Set of available caching strategies for media.
 */
public enum DiskCacheStrategy {
    /** Caches with both {@link #SOURCE} and {@link #RESULT}. */
    ALL(true, true),
    /** Saves no data to cache. */
    NONE(false, false),
    /** Saves just the original data to cache. */
    SOURCE(true, false),
    /** Saves the media item after all transformations to cache. */
    RESULT(false, true);

    private final boolean cacheSource;
    private final boolean cacheResult;

    DiskCacheStrategy(boolean cacheSource, boolean cacheResult) {
        this.cacheSource = cacheSource;
        this.cacheResult = cacheResult;
    }

    /**
     * Returns true if this request should cache the original unmodified data.
     */
    public boolean cacheSource() {
        return cacheSource;
    }

    /**
     * Returns true if this request should cache the final transformed result.
     */
    public boolean cacheResult() {
        return cacheResult;
    }
}

/**
 * Clears disk cache.
 *
 * <p>
 *     This method should always be called on a background thread, since it is a blocking call.
 * </p>
 */
public void clearDiskCache() {
    Util.assertBackgroundThread();
    getEngine().clearDiskCache();
}

/**
 * Clears as much memory as possible.        清理尽可能多的内存
 *
 * @see android.content.ComponentCallbacks#onLowMemory()
 * @see android.content.ComponentCallbacks2#onLowMemory()
 */
public void clearMemory() {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be cleared before bitmap pool to clear re-pooled Bitmaps too. See #687.   // 清楚前位图内存缓存池
    memoryCache.clearMemory();
    bitmapPool.clearMemory();
}
/**
 * Evict all items from the memory cache.   从内存驱逐所有缓存
 */
void clearMemory();
/**
 * Removes all {@link android.graphics.Bitmap}s from the pool. 从池中删除所有位图
 */
void clearMemory();


加载圆形图片:

public class GlideCircleTransform extends BitmapTransformation {


    private static Paint mBorderPaint;
    private static float mBorderWidth;


    public GlideCircleTransform(Context context) {
        super(context);
    }


    public GlideCircleTransform(Context context, int borderWidth, int borderColor) {
        super(context);
        mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;


        mBorderPaint = new Paint();
        mBorderPaint.setDither(true);
        mBorderPaint.setAntiAlias(true);
        mBorderPaint.setColor(borderColor);
        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setStrokeWidth(mBorderWidth);
    }


    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }


    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;


        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;


        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);


        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }


        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        if (mBorderPaint != null) {
            float borderRadius = r - mBorderWidth / 2;
            canvas.drawCircle(r, r, borderRadius, mBorderPaint);
        }
        return result;
    }


    @Override public String getId() {
        return getClass().getName();
    }
}


加载圆角图片:

public class GlideRoundTransform extends BitmapTransformation {

    private static float radius = 0f;

    public GlideRoundTransform(Context context) {
        this(context, 4);
    }

    public GlideRoundTransform(Context context, int dp) {
        super(context);
        this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
    }

    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    @Override public String getId() {
        return getClass().getName() + Math.round(radius);
    }
}


  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值