您的位置:首页 > 移动开发 > Android开发

picasso 将图片裁剪成一个正方形

2017-01-18 18:54 344 查看
实现picasso 中的转换方法
裁剪后缩放 

public class TransformSquare implements Transformation {
    private  float size;
    private  String key;

    public TransformSquare(float size, String key) {
        this.size = size;
        this.key = key;
    }

    /**
     * @param source 需要加工的图片
     * @return
     */
    @Override
    public Bitmap transform(Bitmap source) {
        int height = source.getHeight();
        int width = source.getWidth();
        Bitmap target = null;
        Matrix matrix = new Matrix();

        //宽高相等
        if (height == width) {
            float scale = 1.0f * size / width;
            //设置x,y缩放比例
            matrix.setScale(scale, scale);
            target = Bitmap.createBitmap(source, 0, 0, width, height, matrix, false);
        //宽高不相等
        } else {
            int fromX = 0, fromY = 0;
            int fSize = 0;
            //确定正方形变长
            fSize = Math.min(width, height);
            //计算正方形在原图  的开始裁剪点
            fromX = ((width - fSize) / 2);
            fromY = ((height - fSize) / 2);
            //先剪出一个正方形
            Bitmap bitmap = Bitmap.createBitmap(source, fromX, fromY, fSize, fSize);
            float scale = 1.0f * size / fSize;
            //设置x,y缩放比例
            matrix.setScale(scale, scale);
            target = Bitmap.createBitmap(bitmap, 0, 0, fSize, fSize, matrix, false);
            bitmap.recycle();
        }
        source.recycle();
        return target;
    }

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

   

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐