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; } }
相关文章推荐
- Android 自定义圆形头像CircleImageView支持加载网络图片的实现代码
- 【Android自定义View实战】之自定义圆形头像CircleImageView支持加载网络图片
- Android自定义ImageView实现图片缩放滑动,双击放大缩小,多点触控旋转,圆角矩形,圆形和仿刮刮卡效果
- Android自定义ImageView实现图片缩放滑动,双击放大缩小,多点触控缩放
- android 自定义ImageView实现图片缩放边界回弹和缩小回弹
- Android 详解实现TextView加载带图片标签的Html并按比例缩放
- 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)
- [AndroidUI]自定义view(四):实现圆形圆角图片
- Android-自定义TextView和异步加载图片的实现
- Android自定义View实现图片显示,并实现缩放、拖拽、切换功能
- Android自定义view实现圆形、圆角和椭圆图片(BitmapShader图形渲染)
- android ImageView关于网络加载图片圆形处理
- Android 自定义View修炼-Android实现圆形、圆角和椭圆自定义图片View(使用BitmapShader图形渲染方法)
- Android-图片预览(自定义ImageView实现图片缩放,多点触控,自由移动)
- android 自定义ImageView实现圆形压缩图片
- Android-自定义TextView和异步加载图片的实现
- android自定义View实现图片的绘制、旋转、缩放
- Android-自定义TextView和异步加载图片的实现
- android 自定义ImageView实现图片手势滑动、多点触摸缩放
- android的ViewPager实现加载网络图片并自动轮播