现在在做一个项目,要加载gif动图,查找了好多关于这方面的知识,终于解决了,为了下次能用的上,也为了能够帮助其他人,写下这篇博客。
- 布局代码如下:
<RelativeLayout
android:id="@+id/img_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="#FFF"
android:visibility="visible">
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="@null"
android:scaleType="centerCrop" />
<ImageView
android:id="@+id/iv_gif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="@null"
android:src="@drawable/ic_play_gif"
android:visibility="gone" />
</RelativeLayout>
- 接下来就看看MainActivity中的代码了:
public class MainActivity extends Activity {
private ImageView iv;
private ImageView ivGif;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
ivGif= (ImageView) findViewById(R.id.ivGif);
//初始化volley
ImageLoadProxy.initImageLoader(this);
if (url.endsWith(".gif")) {
ivGif.setVisibility(View.VISIBLE);
} else {
ivGif.setVisibility(View.GONE);
}
ImageLoadProxy.displayImage4Detail(url, iv, new SimpleImageLoadingListener(){
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
//这里可以隐藏进度条哦
}
},
new ImageLoadingProgressListener() {
@Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
//可以显示进度条哦
}
});
);
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点击调整到大图
Intent intent = new Intent(MainActivity.this,PICtureDetailActivity.class);
intent.putExtra("picurl", url);
startActivity(intent);
}
});
}
}
- 图片详情页PictureDetailActivity布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webview"
android:visibility="visible"/>
<!-- PhotoView用到的是第三方jar包 -->
<uk.co.senab.photoview.PhotoView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
/>
</RelativeLayout>
- 图片详情页具体代码
public class PictureDetailActivity extends BaseActivity{
private WebView webView;
private PhotoView img;
private File imgCacheFile;
@Override
public int bindLayout() {
return R.layout.activity_detail_picture;
}
@SuppressLint("JavascriptInterface")
@Override
public void initView(View view) {
Intent intent = getIntent();
final String picUrl = intent.getStringExtra("picurl");
webView = (WebView) findViewById(R.id.webview);
img = (PhotoView) findViewById(R.id.img);
if(picUrl.endsWith(".gif")){
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(this, "external");
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient());
webView.setBackgroundColor(Color.BLACK);
img.setVisibility(View.GONE);
ImageLoadProxy.displayImage4Detail(picUrl, img, new
SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
imgCacheFile = DiskCacheUtils.findInCache(picUrl, ImageLoadProxy.getImageLoader().getDiskCache());
if (imgCacheFile != null) {
String imgPath = "file://" + imgCacheFile.getAbsolutePath();
showImgInWebView(imgPath);
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
});
}
else{
ImageLoadProxy.loadImageFromLocalCache(picUrl, new
SimpleImageLoadingListener() {
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage.getHeight() > UIUtils
.getScreenWidth(PictureDetailActivity.this)) {
imgCacheFile = DiskCacheUtils.findInCache(picUrl, ImageLoadProxy.getImageLoader().getDiskCache());
if (imgCacheFile != null) {
String imgPath = "file://" + imgCacheFile.getAbsolutePath();
img.setVisibility(View.GONE);
showImgInWebView(imgPath);
}
} else {
img.setImageBitmap(loadedImage);
}
}
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
});
}
}
protected void showImgInWebView(String imgPath) {
if (webView != null) {
webView.loadDataWithBaseURL("", "<!doctype html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title></title><style type=\"text/css\"> html,body{width:100%;height:100%;margin:0;padding:0;background-color:black;} *{ -webkit-tap-highlight-color: rgba(0, 0, 0, 0);}#box{ width:100%;height:100%; display:table; text-align:center; background-color:black;} body{-webkit-user-select: none;user-select: none;-khtml-user-select: none;}#box span{ display:table-cell; vertical-align:middle;} #box img{ width:100%;} </style> </head> <body> <div id=\"box\"><span><img src=\"img_url\" alt=\"\"></span></div> <script type=\"text/javascript\" >document.body.onclick=function(e){window.external.onClick();e.preventDefault(); };function load_img(){var url=document.getElementsByTagName(\"img\")[0];url=url.getAttribute(\"src\");var img=new Image();img.src=url;if(img.complete){\twindow.external.img_has_loaded();\treturn;};img.onload=function(){window.external.img_has_loaded();};img.onerror=function(){\twindow.external.img_loaded_error();};};load_img();</script></body> </html>".replace("img_url", imgPath), "text/html", "utf-8", "");
}
}
}
- 接下来把ImageLoadProxy代码也写下来把,注意,图片加载用到到的是volley第三方jar包,可以根据不同的需要,选择不同的方法加载图片
/**
* 图片加载工具类
* @author MegaBest_Panzhiming
*
*/
public class ImageLoadProxy {
private static final int MAX_DISK_CACHE = 1024 * 1024 * 50;
private static final int MAX_MEMORY_CACHE = 1024 * 1024 * 10;
private static boolean isShowLog = false;
private static ImageLoader imageLoader;
public static ImageLoader getImageLoader() {
if(imageLoader == null){
synchronized (ImageLoadProxy.class) {
if(imageLoader == null){
imageLoader = ImageLoader.getInstance();
}
}
}
return imageLoader;
}
public static void initImageLoader(Context context) {
ImageLoaderConfiguration.Builder build = new ImageLoaderConfiguration.Builder(context);
build.tasksProcessingOrder(QueueProcessingType.LIFO);
build.diskCacheSize(MAX_DISK_CACHE);
build.memoryCacheSize(MAX_MEMORY_CACHE);
build.memoryCache(new LruMemoryCache(MAX_MEMORY_CACHE));
if (BuildConfig.DEBUG && isShowLog) {
build.writeDebugLogs();
}
getImageLoader().init(build.build());
}
/**
* 自定义Option
*
* @param url
* @param target
* @param options
*/
public static void displayImage(String url, ImageView target, DisplayImageOptions options) {
imageLoader.displayImage(url, target, options);
}
/**
* 头像专用
*
* @param url
* @param target
*/
public static void displayHeadIcon(String url, ImageView target) {
imageLoader.displayImage(url, target, getOptions4Header());
}
/**
* 图片详情页专用
*
* @param url
* @param target
* @param loadingListener
*/
public static void displayImage4Detail(String url, ImageView target, SimpleImageLoadingListener loadingListener) {
imageLoader.displayImage(url, target, getOption4ExactlyType(), loadingListener);
}
/**
* 图片列表页专用
* @param url
* @param target
* @param loadingResource
* @param loadingListener
* @param progressListener
*/
public static void displayImageList(String url, ImageView target, int loadingResource, SimpleImageLoadingListener loadingListener, ImageLoadingProgressListener progressListener) {
imageLoader.displayImage(url, target, getOptions4PictureList(loadingResource), loadingListener, progressListener);
}
/**
* 自定义加载中图片
*
* @param url
* @param target
* @param loadingResource
*/
public static void displayImageWithLoadingPicture(String url, ImageView target, int loadingResource) {
imageLoader.displayImage(url, target, getOptions4PictureList(loadingResource));
}
/**
* 当使用WebView加载大图的时候,使用本方法现下载到本地然后再加载
*
* @param url
* @param loadingListener
*/
public static void loadImageFromLocalCache(String url, SimpleImageLoadingListener loadingListener) {
imageLoader.loadImage(url, getOption4ExactlyType(), loadingListener);
}
/**
* 设置图片放缩类型为模式EXACTLY,用于图片详情页的缩放
*
* @return
*/
public static DisplayImageOptions getOption4ExactlyType() {
return new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.resetViewBeforeLoading(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.EXACTLY)
.build();
}
/**
* 加载头像专用Options,默认加载中、失败和空url为 ic_loading_small
*
* @return
*/
public static DisplayImageOptions getOptions4Header() {
return new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.showImageOnLoading(R.drawable.ic_launcher)
.build();
}
/**
* 加载图片列表专用,加载前会重置View
* {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#resetViewBeforeLoading} = true
*
* @param loadingResource
* @return
*/
public static DisplayImageOptions getOptions4PictureList(int loadingResource) {
return new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.resetViewBeforeLoading(true)
.showImageOnLoading(loadingResource)
.showImageForEmptyUri(loadingResource)
.showImageOnFail(loadingResource)
.build();
}
}
Volley PhotoView这两个第三方jar包,可以在网上下载,我就不给出链接了。
本文记录了一个项目中加载GIF动图的过程,通过布局和MainActivity代码展示了解决方案。使用了Volley库结合PhotoView来实现,帮助开发者理解和应用相关技术。
5195

被折叠的 条评论
为什么被折叠?



