通過Picasso提供的Transformation實作
圓角矩形
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import com.squareup.picasso.Transformation;
public class PicassoRoundTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int widthLight = source.getWidth();
int heightLight = source.getHeight();
Bitmap output = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paintColor = new Paint();
paintColor.setFlags(Paint.ANTI_ALIAS_FLAG);
RectF rectF = new RectF(new Rect(0, 0, widthLight, heightLight));
canvas.drawRoundRect(rectF, widthLight / 5, heightLight / 5, paintColor);
Paint paintImage = new Paint();
paintImage.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
canvas.drawBitmap(source, 0, 0, paintImage);
source.recycle();
return output;
}
@Override
public String key() {
return "roundcorner";
}
}
用法:
Picasso.with(UserDetialActivity.this).load(imageId).error(R.mipmap.ic_launcher).transform(new PicassoRoundTransform()).into(user_detail_header);
圓形圖檔:
<pre style="background-color: rgb(255, 255, 255);"><pre><span style="font-family:FangSong_GB2312;font-size:12px;">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";
}
}</span>