package com.example.dell.myapplication;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MyImageView extends ImageView {
private String imagePath;
//是否启用缓存
public boolean isUseCache = false;
public static final int GET_DATA_SUCCESS = 1;
public static final int NETWORK_ERROR = 2;
public static final int SERVER_ERROR = 3;
//子线程不能操作UI,通过Handler设置图片
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GET_DATA_SUCCESS:
Bitmap bitmap = (Bitmap) msg.obj;
setImageBitmap(bitmap);
break;
case NETWORK_ERROR:
Toast.makeText(getContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
break;
case SERVER_ERROR:
Toast.makeText(getContext(), "服务器发生错误", Toast.LENGTH_SHORT).show();
break;
}
}
};
public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
//设置网络图片
public void setImageURL(String path) {
imagePath = path;
if (isUseCache){
useCacheImage();
}else {
useNetWorkImage();
}
}
//使用网络图片显示
public void useNetWorkImage(){
//开启一个线程用于联网
new Thread() {
@Override
public void run() {
try {
//把传过来的路径转成URL
URL url = new URL(imagePath);
//获取连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//使用GET方法访问网络
connection.setRequestMethod("GET");
//超时时间为10秒
connection.setConnectTimeout(10000);
//获取返回码
int code = connection.getResponseCode();
if (code == 200) {
Bitmap bitmap;
//获取网络输入流
InputStream inputStream = connection.getInputStream();
//判断是否使用缓存图片
if (isUseCache){
//因为InputStream要使用两次,但是使用一次就无效了,所以需要复制两个
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
//复制新的输入流
InputStream is = new ByteArrayInputStream(baos.toByteArray());
InputStream is2 = new ByteArrayInputStream(baos.toByteArray());
//调用压缩方法显示图片
bitmap = getCompressBitmap(is);
//调用缓存图片方法
cacheImage(is2);
}else {
//调用压缩方法
bitmap = getCompressBitmap(inputStream);
}
//利用Message把图片发给Handler
Message msg = Message.obtain();
msg.obj = bitmap;
msg.what = GET_DATA_SUCCESS;
handler.sendMessage(msg);
inputStream.close();
} else {
//服务启发生错误
handler.sendEmptyMessage(SERVER_ERROR);
}
} catch (IOException e) {
e.printStackTrace();
//网络连接错误
handler.sendEmptyMessage(NETWORK_ERROR);
}
}
}.start();
}
//使用缓存图片
public void useCacheImage() {
//创建路径一样的文件
File file = new File(getContext().getCacheDir(), getURLPath());
//判断文件是否存在
if (file != null && file.length() > 0) {
//使用本地图片
try {
InputStream inputStream = new FileInputStream(file);
//调用压缩方法显示图片
Bitmap bitmap = getCompressBitmap(inputStream);
//利用Message把图片发给Handler
Message msg = Message.obtain();
msg.obj = bitmap;
msg.what = GET_DATA_SUCCESS;
handler.sendMessage(msg);
Log.e("MyImageView","使用缓存图片");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else {
//使用网络图片
useNetWorkImage();
Log.e("MyImageView","使用网络图片");
}
}
/**
* 缓存网络的图片
* @param inputStream 网络的输入流
*/
public void cacheImage(InputStream inputStream) {
try {
File file = new File(getContext().getCacheDir(), getURLPath());
FileOutputStream fos = new FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
Log.e("MyImageView","缓存成功");
} catch (IOException e) {
e.printStackTrace();
Log.e("MyImageView","缓存失败");
}
}
/**
* 根据网址生成一个文件名
* @return 文件名
*/
public String getURLPath() {
StringBuilder urlStr2 = new StringBuilder();
String[] strings = imagePath.split("\\/");
for (String string : strings) {
urlStr2.append(string);
}
Log.e("MyImageView","文件名:"+urlStr2.toString());
return urlStr2.toString();
}
/**
* 根据输入流返回一个压缩的图片
*
* @param input 图片的输入流
* @return 压缩的图片
*/
public Bitmap getCompressBitmap(InputStream input) {
//因为InputStream要使用两次,但是使用一次就无效了,所以需要复制两个
ByteArrayOutputStream baos =
没有合适的资源?快使用搜索试试~ 我知道了~
自定义ImageView
共74个文件
xml:41个
bin:6个
png:5个
4星 · 超过85%的资源 需积分: 9 64 下载量 27 浏览量
2017-08-11
14:03:31
上传
评论
收藏 235KB RAR 举报
温馨提示
自定义ImageView方法
资源推荐
资源详情
资源评论
收起资源包目录
自定义ImageView.rar (74个子文件)
MyApplication6
gradlew.bat 2KB
gradlew 5KB
gradle.properties 747B
.gradle
2.14.1
tasks
_app_compileDebugJavaWithJavac
localJarClasspathSnapshot
localJarClasspathSnapshot.bin 20KB
localJarClasspathSnapshot.lock 17B
localClassSetAnalysis
localClassSetAnalysis.lock 17B
localClassSetAnalysis.bin 47KB
taskArtifacts
fileHashes.bin 150KB
cache.properties.lock 17B
taskArtifacts.bin 145KB
fileSnapshotsToTreeSnapshotsIndex.bin 29KB
fileSnapshots.bin 3.88MB
cache.properties 31B
app
proguard-rules.pro 662B
src
test
java
com
example
dell
myapplication
ExampleUnitTest.java 816B
androidTest
java
com
example
dell
myapplication
ExampleInstrumentedTest.java 790B
main
res
mipmap-xxxhdpi
ic_launcher.png 10KB
drawable
mipmap-hdpi
ic_launcher.png 3KB
values
colors.xml 214B
strings.xml 80B
styles.xml 394B
dimens.xml 216B
mipmap-xxhdpi
ic_launcher.png 8KB
mipmap-mdpi
ic_launcher.png 2KB
mipmap-xhdpi
ic_launcher.png 5KB
layout
activity_main.xml 778B
values-w820dp
dimens.xml 364B
java
com
example
dell
myapplication
MyImageView.java 12KB
MainActivity.java 1KB
AndroidManifest.xml 756B
app.iml 13KB
.gitignore 8B
build.gradle 960B
libs
gradle
wrapper
gradle-wrapper.jar 52KB
gradle-wrapper.properties 233B
.idea
gradle.xml 626B
runConfigurations.xml 564B
misc.xml 2KB
copyright
profiles_settings.xml 76B
modules.xml 365B
compiler.xml 686B
workspace.xml 173KB
libraries
javawriter_2_1_1.xml 330B
jsr305_2_0_1.xml 330B
support_annotations_25_3_1.xml 495B
support_v4_25_3_1.xml 420B
support_vector_drawable_25_3_1.xml 640B
rules_0_5.xml 721B
javax_annotation_api_1_2.xml 358B
gifdecoder_4_0_0.xml 547B
runner_0_5.xml 727B
glide_4_0_0.xml 522B
hamcrest_library_1_3.xml 342B
espresso_idling_resource_2_2_2.xml 682B
support_core_utils_25_3_1.xml 797B
animated_vector_drawable_25_3_1.xml 645B
hamcrest_core_1_3.xml 526B
junit_4_12.xml 477B
support_compat_25_3_1.xml 773B
support_core_ui_25_3_1.xml 779B
disklrucache_4_0_0.xml 557B
appcompat_v7_25_3_1.xml 761B
support_media_compat_25_3_1.xml 809B
support_fragment_25_3_1.xml 785B
annotations_4_0_0.xml 552B
hamcrest_integration_1_3.xml 354B
espresso_core_2_2_2.xml 627B
javax_inject_1.xml 324B
exposed_instrumentation_api_publish_0_5.xml 700B
.gitignore 127B
local.properties 428B
settings.gradle 16B
build.gradle 521B
MyApplication6.iml 868B
共 74 条
- 1
资源评论
- arhuan1262019-02-25可以简单的学习一下
夜雨飘零1
- 粉丝: 2811
- 资源: 108
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功