先上效果图
Glide
在app的build.gradle中引入: // 加载图片 implementation 'com.github.bumptech.glide:glide:4.13.1'
// 如果涉及到网络加载图片,需要在manifest.xml文件中增加网络权限 <uses-permission android:name="android.permission.INTERNET" />
// 直接在java文件中引用库就OK /** * context:Context(with参数类型可以为Context、Activity、FragmentActivity、Fragment、View) * uri:Uri(load参数类型可以为Bitmap、Drawable、String、Uri、File、Integer、URL、byte[]、Object) * apply:RequestOptions.bitmapTransform(new CircleCrop()):加载圆形图片 * imageView:控件id */ Glide.with(context).load(uri).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imageView);
Picasso
在app的build.gradle中引入: // 加载网络图片相关 implementation "com.squareup.picasso:picasso:2.5.2" • 1 • 2 • 3
// 直接在java文件中引用 /** * context:Context * uri:Uri(load参数类型可以为String、Uri、File、int) * transform:new CircleTransform():圆形图片工具类(下文有) * imageView:控件id */ Picasso.with(context).load(uri).transform(new CircleTransform()).into(imageView);
CircleTransform.java(圆形图片工具类)
package com.gaojc.top.util; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import com.squareup.picasso.Transformation; /** * 圆形图片 */ public class CircleTransform implements Transformation { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig()); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); paint.setShader(shader); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squaredBitmap.recycle(); return bitmap; } @Override public String key() { return "circle"; } }