Android--自定义View加载网络图片,实现缩放,圆形剪裁

功能:加载网络图片,本地资源图片,圆形剪裁,图片自动缩放

package com.example.administrator.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/6/28.
 */

public class HeadView extends View {
    private static final int SUCCESS = 101;
    private static final int FAILED = 102;
    private String fileName;
    private Bitmap img;
    private boolean makeCircle = false;
    private Paint paint = new Paint();
    private Rect src = new Rect();
    private Rect dst = new Rect();
    private Path path = new Path();
    private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    invalidate();
                    if (loadListener != null) {
                        loadListener.onSuccess();
                    }
                    saveBitmap(fileName);
                    break;
                case FAILED:
                    L.e("加载失败!");
                    if (loadListener != null) {
                        loadListener.onFailed();
                    }
                    break;
                default:break;
            }
        }
    };

    public HeadView(Context context) {
        super(context);
        init();
    }

    public HeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init() {
        paint.setAntiAlias(true);
        paint.setStrokeWidth(40);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int w,h;
        if (widthMode == MeasureSpec.EXACTLY) {
            w = width;
        } else {
            w = 200;
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            h = height;
        } else {
            h = 200;
        }
        setMeasuredDimension(w,h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (img != null) {
            int width = getWidth();
            int height = getHeight();
            int w = img.getWidth();
            int h = img.getHeight();

            if (makeCircle) {
                int x = width >> 1;
                int y = height >> 1;
                int radius = (width < height? width : height) >> 1;
                path.addCircle(x, y, radius, Path.Direction.CW);
                canvas.clipPath(path);
                dst.set(x -radius, y - radius, x + radius, y + radius);

                radius = (w < h? w : h) >> 1;
                x = w >> 1;
                y = h >> 1;
                src.set(x -radius, y - radius, x + radius , y + radius);
                canvas.drawBitmap(img, src, dst, paint);
                return;
            }

            float scale;
            if (w < width && h < height) {
                scale = 1.1f;
                while (w * scale < width && h * scale < height) {
                    w *= scale;
                    h *= scale;
                }
            } else {
                scale = 0.9f;
                while (w > width || h > height) {
                    w *= scale;
                    h *= scale;
                }
            }
            int left = (width - w) >> 1;
            int top = (height - h) >> 1;
            int right = width - left;
            int bottom = height - top;
            dst.set(left, top, right, bottom);
            canvas.drawBitmap(img, null, dst, paint);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        L.e("onDetachedFromWindow start");
        if (img != null) {
            img.recycle();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        L.e("onDetachedFromWindow end");
        super.onDetachedFromWindow();
    }

    public void setImageFromNet(final String url) {
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                InputStream bis = null;
                ByteArrayOutputStream bos = null;
                try {
                    URL address = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) address.openConnection();
                    conn.connect();
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        bis = conn.getInputStream();
                        bos = new ByteArrayOutputStream();
                        int len;
                        byte[] array = new byte[4096];
                        while ((len = bis.read(array)) != - 1) {
                            bos.write(array, 0, len);
                        }
                        fileName = subUrlForName(url);
                        byte[] data = bos.toByteArray();
                        img = BitmapFactory.decodeByteArray(data, 0, data.length);
                        conn.disconnect();
                        bis.close();
                        bos.close();
                        handler.sendEmptyMessage(SUCCESS);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(FAILED);
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    if (bos != null) {
                        try {
                            bos.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    public void saveBitmap(String name) {
        FileOutputStream fos = null;
        if (img != null) {
            try {
                fos = new FileOutputStream(getContext().getFileStreamPath(name));
                img.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    private String subUrlForName(String url) {
        if (!TextUtils.isEmpty(url)) {
            return url.substring(url.lastIndexOf("/")+1, url.length());
        } else {
            return "";
        }
    }

    public void setImage(String url) {
        if (!TextUtils.isEmpty(url)) {
            String name = subUrlForName(url);
            File file = getContext().getFileStreamPath(name);
            if (file.exists()) {
                L.e("second cache");
                if (img != null) {
                    img.recycle();
                }
                img = BitmapFactory.decodeFile(getContext().getFileStreamPath(name).getAbsolutePath());
                invalidate();
                handler.sendEmptyMessage(SUCCESS);
            } else {
                L.e("third cache");
                setImageFromNet(url);
            }
        }
    }

    public void setImg(int id) {
        img = BitmapFactory.decodeResource(getResources(), id);
        invalidate();
    }

    public void setCircleImage() {
        makeCircle = true;
        path = new Path();
        invalidate();
    }

    private LoadListener loadListener;

    public interface LoadListener {
        void onSuccess();
        void onFailed();
    }

    public void setLoadListener(LoadListener loadListener) {
        this.loadListener = loadListener;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值