您的位置:首页 > 理论基础 > 计算机网络

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

2017-06-30 11:58 741 查看
功能:加载网络图片,本地资源图片,圆形剪裁,图片自动缩放


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