Glide 是 Google 员工的开源项目, Google I/O 上被推荐使用,一个高效、开源、Android设备上的媒体管理框架,它遵循BSD、MIT以及Apache 2.0协议发布。Glide具有获取、解码和展示视频剧照、图片、动画等功能,它还有灵活的API,这些API使开发者能够将Glide应用在几乎任何网络协议栈里。创建Glide的主要目的有两个,一个是实现平滑的图片列表滚动效果,另一个是支持远程图片的获取、大小调整和展示。
Glide的一般使用相信大家都知道,主要侧重怎么封装使用,看二就行了
一、Glide使用
依赖
需要support-v4库的支持,如果你的项目没有support-v4库(项目默认已经添加了),还需要添加support-v4依赖
compile 'com.android.support:support-v4:25.2.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
简单使用:
Glide
.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.into(imageView);
Glide.with()使用
with(Context context). 使用Application上下文,Glide请求将不受Activity/Fragment生命周期控制。
with(Activity activity).使用Activity作为上下文,Glide的请求会受到Activity生命周期控制。
with(FragmentActivity activity).Glide的请求会受到FragmentActivity生命周期控制。
with(android.app.Fragment fragment).Glide的请求会受到Fragment 生命周期控制。
with(android.support.v4.app.Fragment fragment).Glide的请求会受到Fragment生命周期控制。
requestManager.load()使用
Glide基本可以load任何可以拿到的媒体资源,如:
- loadSD卡资源:load("file://"+ Environment.getExternalStorageDirectory().getPath()+"/test.jpg")
- loadassets资源:load("file:///android_asset/f003.gif")
- loadraw资源:load("Android.resource://com.frank.glide/raw/raw_1")或load("android.resource://com.frank.glide/raw/"+R.raw.raw_1)
- loaddrawable资源:load("android.resource://com.frank.glide/drawable/news")或load("android.resource://com.frank.glide/drawable/"+R.drawable.news)
- loadContentProvider资源:load("content://media/external/images/media/139469")
- loadhttp资源:load("http://img.my.csdn.net/uploads/201508/05/1438760757_3588.jpg")
- loadhttps资源:load("https://img.alicdn.com/tps/TB1uyhoMpXXXXcLXVXXXXXXXXXX-476-538.jpg_240x5000q50.jpg_.webp")
load不限于String类型,还可以:
load(Uri uri),load(File file),load(Integer resourceId),load(URL url),load(byte[] model),load(T model),loadFromMediaStore(Uri uri)。
load的资源也可以是本地视频,如果想要load网络视频或更高级的操作可以使用VideoView等其它控件完成
GenericRequestBuilder使用
GenericRequestBuilder<ModelType,DataType,ResourceType,TranscodeType>
是最顶层的Request Builder,用于处理选项设置和开始一般resource类型资源的加载。其中ModelType
是指代表资源的类型,如"http://img.my.csdn.net/uploads/201508/05/1438760757_3588.jpg"这个String就代表了一张图片资源,所以这个ModelType就是String。DataType
是指ModelLoader提供的,可以被ResourceDecoder解码的数据类型。ResourceType
是指将要加载的resource类型。TranscodeType
是指已解码的资源将要被转成的资源类型。
1、thumbnail(float sizeMultiplier). 请求给定系数的缩略图。如果缩略图比全尺寸图先加载完,就显示缩略图,否则就不显示。系数sizeMultiplier必须在(0,1)之间,可以递归调用该方法。
2、sizeMultiplier(float sizeMultiplier). 在加载资源之前给Target大小设置系数。
3、diskCacheStrategy(DiskCacheStrategy strategy).设置缓存策略。DiskCacheStrategy.SOURCE:缓存原始数据,DiskCacheStrategy.RESULT:缓存变换(如缩放、裁剪等)后的资源数据,DiskCacheStrategy.NONE:什么都不缓存,DiskCacheStrategy.ALL:缓存SOURC和RESULT。默认采用DiskCacheStrategy.RESULT策略,对于download only操作要使用DiskCacheStrategy.SOURCE。
4、priority(Priority priority). 指定加载的优先级,优先级越高越优先加载,但不保证所有图片都按序加载。枚举Priority.IMMEDIATE,Priority.HIGH,Priority.NORMAL,Priority.LOW。默认为Priority.NORMAL。
5、dontAnimate(). 移除所有的动画。
6、animate(int animationId). 在异步加载资源完成时会执行该动画。
7、animate(ViewPropertyAnimation.Animator animator). 在异步加载资源完成时会执行该动画。
8、placeholder(int resourceId). 设置资源加载过程中的占位Drawable。
9、placeholder(Drawable drawable). 设置资源加载过程中的占位Drawable。
10、fallback(int resourceId). 设置model为空时要显示的Drawable。如果没设置fallback,model为空时将显示error的Drawable,如果error的Drawable也没设置,就显示placeholder的Drawable。
11、fallback(Drawable drawable).设置model为空时显示的Drawable。
12、error(int resourceId).设置load失败时显示的Drawable。
13、error(Drawable drawable).设置load失败时显示的Drawable。
14、listener(RequestListener<? super ModelType, TranscodeType> requestListener). 监听资源加载的请求状态,可以使用两个回调:onResourceReady(R resource, T model, Target<R> target, boolean isFromMemoryCache, boolean isFirstResource)
和onException(Exception e, T model, Target<R> target, boolean isFirstResource)
,但不要每次请求都使用新的监听器,要避免不必要的内存申请,可以使用单例进行统一的异常监听和处理。
15、skipMemoryCache(boolean skip). 设置是否跳过内存缓存,但不保证一定不被缓存(比如请求已经在加载资源且没设置跳过内存缓存,这个资源就会被缓存在内存中)。
16、override(int width, int height). 重新设置Target的宽高值(单位为pixel)。
17、into(Y target).设置资源将被加载到的Target。
18、into(ImageView view). 设置资源将被加载到的ImageView。取消该ImageView之前所有的加载并释放资源。
19、into(int width, int height). 后台线程加载时要加载资源的宽高值(单位为pixel)。
20、preload(int width, int height). 预加载resource到缓存中(单位为pixel)。
21、asBitmap(). 无论资源是不是gif动画,都作为Bitmap对待。如果是gif动画会停在第一帧。
22、asGif().把资源作为GifDrawable对待。如果资源不是gif动画将会失败,会回调.error()
。
具体使用:
1、禁止内存缓存:
.skipMemoryCache(true)
2、清除内存缓存:
// 必须在UI线程中调用
Glide.get(context).clearMemory();
3、禁止磁盘缓存:
.diskCacheStrategy(DiskCacheStrategy.NONE)
4、清除磁盘缓存:
// 必须在后台线程中调用,建议同时clearMemory()
Glide.get(applicationContext).clearDiskCache();
5、获取缓存大小:
new GetDiskCacheSizeTask(textView).execute(new File(getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));
class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long> {
private final TextView resultView;
public GetDiskCacheSizeTask(TextView resultView) {
this.resultView = resultView;
}
@Override
protected void onPreExecute() {
resultView.setText("Calculating...");
}
@Override
protected void onProgressUpdate(Long... values) { /* onPostExecute(values[values.length - 1]); */ }
@Override
protected Long doInBackground(File... dirs) {
try {
long totalSize = 0;
for (File dir : dirs) {
publishProgress(totalSize);
totalSize += calculateSize(dir);
}
return totalSize;
} catch (RuntimeException ex) {
final String message = String.format("Cannot get size of %s: %s", Arrays.toString(dirs), ex);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
resultView.setText("error");
Toast.makeText(resultView.getContext(), message, Toast.LENGTH_LONG).show();
}
});
}
return 0L;
}
@Override
protected void onPostExecute(Long size) {
String sizeText = android.text.format.Formatter.formatFileSize(resultView.getContext(), size);
resultView.setText(sizeText);
}
private static long calculateSize(File dir) {
if (dir == null) return 0;
if (!dir.isDirectory()) return dir.length();
long result = 0;
File[] children = dir.listFiles();
if (children != null)
for (File child : children)
result += calculateSize(child);
return result;
}
}
6、指定资源的优先加载顺序:
//优先加载
Glide
.with(context)
.load(heroImageUrl)
.priority(Priority.HIGH)
.into(imageViewHero);
//后加载
Glide
.with(context)
.load(itemImageUrl)
.priority(Priority.LOW)
.into(imageViewItem);
7、先显示缩略图,再显示原图:
//用原图的1/10作为缩略图
Glide
.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.thumbnail(0.1f)
.into(iv_0);
//用其它图片作为缩略图
DrawableRequestBuilder<Integer> thumbnailRequest = Glide
.with(this)
.load(R.drawable.news);
Glide.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.thumbnail(thumbnailRequest)
.into(iv_0);
8、bitmapTransform使用,可对图片裁剪、滤镜、灰度等等
(使用时只需使用transform()或bitmapTransform()方法即可)
//圆形裁剪
Glide.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.bitmapTransform(new CropCircleTransformation(this))
.into(iv_0);
//圆角处理
Glide.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.bitmapTransform(new RoundedCornersTransformation(this,30,0, RoundedCornersTransformation.CornerType.ALL))
.into(iv_0);
//灰度处理
Glide.with(this)
.load("http://inthecheesefactory.com/uploads/source/nestedfragment/fragments.png")
.bitmapTransform(new GrayscaleTransformation(this))
.into(iv_0);
图片处理库GitHub:https://github.com/wasabeef/glide-transformations
图片处理库
使用步骤:
Gradle
repositories {
jcenter()
}
dependencies {
compile 'jp.wasabeef:glide-transformations:2.0.2'
// If you want to use the GPU Filters
compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
}
Glide中使用(如高斯模糊)
Glide.with(this).load(R.drawable.demo)
.bitmapTransform(new BlurTransformation(context))
.into((ImageView) findViewById(R.id.image));
添加多种滤镜效果
Glide.with(this).load(R.drawable.demo)
.bitmapTransform(new BlurTransformation(context, 25), new CropCircleTransformation(context))
.into((ImageView) findViewById(R.id.image));
二、自定义工具类介绍
自定义的工具类,是基于Glide的使用之上的
- (1)ImageView设置图片(加载错误图片)
- (2)ImageView设置图片---BitMap(不设置默认图)
- (3)设置RelativeLayout的图片
- (4)设置LinearLayout的图片
- (5)设置FrameLayout的图片
- (6)高斯模糊------ RelativeLayout设置图片
- (7)高斯模糊------ LinearLayout设置图片
- (8)圆角显示图片 ImageView
随便写了几个,可根据需求自定义
使用
- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.nohttpdemo.activity.ImageActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical">
<ImageView
android:id="@+id/cirview"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="20dp"
android:orientation="vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="背景使用高斯模糊,左边图片使用圆角" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下方图片正常显示" />
<RelativeLayout
android:id="@+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="200dp" />
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="20dp" />
</LinearLayout>
</ScrollView>
- Activity中使用
//高斯模糊
ShowImageUtils.showImageViewBlur(this, R.mipmap.ic_launcher, url1, layout);
//圆角
ShowImageUtils.showImageViewToCircle(getApplication(), R.mipmap.ic_launcher, url2, cirview);
//relaytiveLay
ShowImageUtils.showImageView(this, R.mipmap.ic_launcher, url1, relativelayout);
//一般图片,支持imageview,layout
ShowImageUtils.showImageView(this, R.mipmap.ic_launcher, url3, img);
- 效果图
自定义工具类ShowImageUtils
package com.app.nohttpdemo.utils.img;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
/**
* 网络图片的工具类
* <p>
* (1)ImageView设置图片(错误图片)
* (2)ImageView设置图片---BitMap(不设置默认图)
* (3)设置RelativeLayout
* (4)设置LinearLayout
* (5)设置FrameLayout
* (6)高斯模糊------ RelativeLayout
* (7)高斯模糊------ LinearLayout
* (8)圆角显示图片 ImageView
*
* @author huangshuyuan
*/
public class ShowImageUtils {
/**
* (1)
* 显示图片Imageview
*
* @param context 上下文
* @param errorimg 错误的资源图片
* @param url 图片链接
* @param imgeview 组件
*/
public static void showImageView(Context context, int errorimg, String url,
ImageView imgeview) {
Glide.with(context).load(url)// 加载图片
.error(errorimg)// 设置错误图片
.crossFade()// 设置淡入淡出效果,默认300ms,可以传参
.placeholder(errorimg)// 设置占位图
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.into(imgeview);
// Glide.with(context).load(url).thumbnail(0.1f).error(errorimg)
// .into(imgeview);
// Glide
// .with(context)
// .load(UsageExampleListViewAdapter.eatFoodyImages[0])
// .placeholder(R.mipmap.ic_launcher) //设置占位图
// .error(R.mipmap.future_studio_launcher) //设置错误图片
// .crossFade() //设置淡入淡出效果,默认300ms,可以传参
// //.dontAnimate() //不显示动画效果
// .into(imageViewFade);
}
/**
* (2)
* 获取到Bitmap---不设置错误图片,错误图片不显示
*
* @param context
* @param imageView
* @param url
*/
public static void showImageViewGone(Context context,
final ImageView imageView, String url) {
Glide.with(context).load(url).asBitmap()
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
imageView.setVisibility(View.VISIBLE);
BitmapDrawable bd = new BitmapDrawable(loadedImage);
imageView.setImageDrawable(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
imageView.setVisibility(View.GONE);
}
});
}
/**
* (3)
* 设置RelativeLayout
* <p>
* 获取到Bitmap
*
* @param context
* @param errorimg
* @param url
* @param bgLayout
*/
public static void showImageView(Context context, int errorimg, String url,
final RelativeLayout bgLayout) {
Glide.with(context).load(url).asBitmap().error(errorimg)// 设置错误图片
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.placeholder(errorimg)// 设置占位图
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
BitmapDrawable bd = new BitmapDrawable(loadedImage);
bgLayout.setBackground(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
bgLayout.setBackgroundDrawable(errorDrawable);
}
});
}
/**
* (4)
* 设置LinearLayout
* <p>
* 获取到Bitmap
*
* @param context
* @param errorimg
* @param url
* @param bgLayout
*/
public static void showImageView(Context context, int errorimg, String url,
final LinearLayout bgLayout) {
Glide.with(context).load(url).asBitmap().error(errorimg)// 设置错误图片
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.placeholder(errorimg)// 设置占位图
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
BitmapDrawable bd = new BitmapDrawable(loadedImage);
bgLayout.setBackground(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
bgLayout.setBackgroundDrawable(errorDrawable);
}
});
}
/**
* (5)
* 设置FrameLayout
* <p>
* 获取到Bitmap
*
* @param context
* @param errorimg
* @param url
* @param frameBg
*/
public static void showImageView(Context context, int errorimg, String url,
final FrameLayout frameBg) {
Glide.with(context).load(url).asBitmap().error(errorimg)// 设置错误图片
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.placeholder(errorimg)// 设置占位图
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
BitmapDrawable bd = new BitmapDrawable(loadedImage);
frameBg.setBackground(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
frameBg.setBackgroundDrawable(errorDrawable);
}
});
}
/**
* (6)
* 获取到Bitmap 高斯模糊 RelativeLayout
*
* @param context
* @param errorimg
* @param url
* @param bgLayout
*/
public static void showImageViewBlur(Context context, int errorimg,
String url, final RelativeLayout bgLayout) {
Glide.with(context).load(url).asBitmap().error(errorimg)
// 设置错误图片
.diskCacheStrategy(DiskCacheStrategy.RESULT)
// 缓存修改过的图片
.placeholder(errorimg)
.transform(new BlurTransformation(context))// 高斯模糊处理
// 设置占位图
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
BitmapDrawable bd = new BitmapDrawable(loadedImage);
bgLayout.setBackground(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
bgLayout.setBackgroundDrawable(errorDrawable);
}
});
}
/**
* (7)
* 获取到Bitmap 高斯模糊 LinearLayout
*
* @param context
* @param errorimg
* @param url
* @param bgLayout
*/
public static void showImageViewBlur(Context context, int errorimg,
String url, final LinearLayout bgLayout) {
Glide.with(context).load(url).asBitmap().error(errorimg)
// 设置错误图片
.diskCacheStrategy(DiskCacheStrategy.RESULT)
// 缓存修改过的图片
.placeholder(errorimg)
.transform(new BlurTransformation(context))// 高斯模糊处理
// 设置占位图
.into(new SimpleTarget<Bitmap>() {
@SuppressLint("NewApi")
@Override
public void onResourceReady(Bitmap loadedImage,
GlideAnimation<? super Bitmap> arg1) {
BitmapDrawable bd = new BitmapDrawable(loadedImage);
bgLayout.setBackground(bd);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
// TODO Auto-generated method stub
super.onLoadFailed(e, errorDrawable);
bgLayout.setBackgroundDrawable(errorDrawable);
}
});
}
/**
* (8)
* 显示图片 圆角显示 ImageView
*
* @param context 上下文
* @param errorimg 错误的资源图片
* @param url 图片链接
* @param imgeview 组件
*/
public static void showImageViewToCircle(Application context, int errorimg,
String url, ImageView imgeview) {
Glide.with(context).load(url)
// 加载图片
.error(errorimg)
// 设置错误图片
.crossFade()
// 设置淡入淡出效果,默认300ms,可以传参
.placeholder(errorimg)
// 设置占位图
.transform(new GlideCircleTransform(context))//圆角
.diskCacheStrategy(DiskCacheStrategy.RESULT)// 缓存修改过的图片
.into(imgeview);
// Glide.with(context).load(url).thumbnail(0.1f).error(errorimg)
// .into(imgeview);
// Glide
// .with(context)
// .load(UsageExampleListViewAdapter.eatFoodyImages[0])
// .placeholder(R.mipmap.ic_launcher) //设置占位图
// .error(R.mipmap.future_studio_launcher) //设置错误图片
// .crossFade() //设置淡入淡出效果,默认300ms,可以传参
// //.dontAnimate() //不显示动画效果
// .into(imageViewFade);
}
}
高斯模糊
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.renderscript.RSRuntimeException;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
public class BlurTransformation implements Transformation<Bitmap> {
private static int MAX_RADIUS = 25;
private static int DEFAULT_DOWN_SAMPLING = 1;
private Context mContext;
private BitmapPool mBitmapPool;
private int mRadius;
private int mSampling;
public BlurTransformation(Context context) {
this(context, Glide.get(context).getBitmapPool(), MAX_RADIUS,
DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, BitmapPool pool) {
this(context, pool, MAX_RADIUS, DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, BitmapPool pool, int radius) {
this(context, pool, radius, DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, int radius) {
this(context, Glide.get(context).getBitmapPool(), radius,
DEFAULT_DOWN_SAMPLING);
}
public BlurTransformation(Context context, BitmapPool pool, int radius,
int sampling) {
mContext = context;
mBitmapPool = pool;
mRadius = radius;
mSampling = sampling;
}
public BlurTransformation(Context context, int radius, int sampling) {
mContext = context;
mBitmapPool = Glide.get(context).getBitmapPool();
mRadius = radius;
mSampling = sampling;
}
@Override
public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth,
int outHeight) {
Bitmap source = resource.get();
int width = source.getWidth();
int height = source.getHeight();
int scaledWidth = width / mSampling;
int scaledHeight = height / mSampling;
Bitmap bitmap = mBitmapPool.get(scaledWidth, scaledHeight,
Bitmap.Config.ARGB_8888);
if (bitmap == null) {
bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight,
Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
canvas.scale(1 / (float) mSampling, 1 / (float) mSampling);
Paint paint = new Paint();
paint.setFlags(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(source, 0, 0, paint);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
try {
bitmap = RSBlur.blur(mContext, bitmap, mRadius);
} catch (RSRuntimeException e) {
bitmap = FastBlur.blur(bitmap, mRadius, true);
}
} else {
bitmap = FastBlur.blur(bitmap, mRadius, true);
}
return BitmapResource.obtain(bitmap, mBitmapPool);
}
@Override
public String getId() {
return "BlurTransformation(radius=" + mRadius + ", sampling="
+ mSampling + ")";
}
}
import android.graphics.Bitmap;
public class FastBlur {
public static Bitmap blur(Bitmap sentBitmap, int radius,
boolean canReuseInBitmap) {
Bitmap bitmap;
if (canReuseInBitmap) {
bitmap = sentBitmap;
} else {
bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
}
if (radius < 1) {
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16)
| (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return (bitmap);
}
}
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RSRuntimeException;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
public class RSBlur {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static Bitmap blur(Context context, Bitmap blurredBitmap, int radius)
throws RSRuntimeException {
try {
RenderScript rs = RenderScript.create(context);
Allocation input = Allocation.createFromBitmap(rs, blurredBitmap,
Allocation.MipmapControl.MIPMAP_NONE,
Allocation.USAGE_SCRIPT);
Allocation output = Allocation.createTyped(rs, input.getType());
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs,
Element.U8_4(rs));
blur.setInput(input);
blur.setRadius(radius);
blur.forEach(output);
output.copyTo(blurredBitmap);
rs.destroy();
} catch (RSRuntimeException e) {
blurredBitmap = FastBlur.blur(blurredBitmap, radius, true);
}
return blurredBitmap;
}
}
圆角
直接实现Transformation接口,进行更灵活的图片处理,如进行简单地圆角处理
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
/**
* 圆角Glide
*
* @author Administrator
*/
public class GlideCircleTransform extends BitmapTransformation {
public GlideCircleTransform(Context context) {
super(context);
}
@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);
return result;
}
@Override
public String getId() {
return getClass().getName();
}
我的博客:http://blog.csdn.net/Imshuyuan/article/details/67637643
参考文章:
Glide使用详解(一)
Glide开发文档
Glide详解
我的Demo已上传,GitHub 上Demo地址