Picasso利用Transformation自定义带边框的圆形图片

   目前Picasso图片加载工具也比较流行,很多人会在加载图片时有圆形图片的需求。其实Picasso已经为我们提供了方法去实现,但是具体的实现过程得自己去定义。这里,我们使用BitmapShader来具体实现。BitmapShader的主要作用就是通过Paint对象,对画布进行指定的Bitmap填充,实现一系列效果,可以有以下三种模式进行选择:

  • CLAMP - 拉伸,这里拉伸的是图片的最后一个元素,不断地重复,这个效果,在图片比较小,而所要画的面积比较大的时候会比较明显。
  • REPEAT - 重复,横向纵向不断地重复,不同于上一模式,这种模式在图片比较小不能满足要求是,会在横向纵向不断重复绘制图形。
  • MIRROR - 翻转,这种模式和 REPEAT 是类似的,只不过这里的重复是翻转着重复,和折纸的效果差不多。

而我们将要使用的是 CLAMP 模式,因为只要我们对图形的大小进行控制,就可以避免图像进行拉伸。

  首先我们对Picasso的变形接口Transformation进行实现,主要实现两个接口,一个是transform主要用于变形的实现,一个是key进行标记。具体代码如下:

/**
 * author zhangpan
 * Created by corous360 on 2016/10/19.
 */
public class CircleTransform implements Transformation {

    private int mBorderWidth = 4;  //边框宽度
    private int mBorderColor = R.color.colorAccent;  //边框颜色

    public CircleTransform(){}

    public CircleTransform(int mBorderWidth, int mBorderColor){

        this.mBorderColor = mBorderColor;
        this.mBorderWidth = mBorderWidth;

    }

    @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() != null
                ? source.getConfig() : Bitmap.Config.ARGB_8888);

        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);

        //绘制边框
        Paint mBorderPaint = new Paint();
        mBorderPaint.setStyle(Paint.Style.STROKE);
        mBorderPaint.setStrokeWidth(mBorderWidth);
        mBorderPaint.setColor(MyApplication.mInstance.getResources().getColor(mBorderColor));
        mBorderPaint.setStrokeCap(Paint.Cap.ROUND);
        mBorderPaint.setAntiAlias(true);

        //将边框和圆形画到canvas上
        float r = size / 2f;
        float r1 = (size-2*mBorderWidth) / 2f;
        canvas.drawCircle(r, r, r1, paint);
        canvas.drawCircle(r, r, r1, mBorderPaint);

        squaredBitmap.recycle();
        return bitmap;
    }

    @Override
    public String key() {
        return "Circle";
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值