安卓原生ImageView不怎么好用于是乎,网上搜索了一个模板,为了实现切图的无缝对接,参考了网上的资料之后改装了一下如下:
package com.example.k.myrecyclerview;
/**
* Created by k on 2016/8/11.
*/
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
public class MyImageView extends ImageView {
//屏幕宽
float screen_width;
private Bitmap mBitmap;
//倍数
float Multiple = 0, pic_height = 0, pic_init_width = 0;
float pic_init_height = 0;
private boolean mReady;
private boolean mSetupPending;
public MyImageView(Context context) {
super(context);
init();
}
public MyImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//得到屏幕的宽度
WindowManager wm = (WindowManager) getContext()
.getSystemService(Context.WINDOW_SERVICE);
screen_width = wm.getDefaultDisplay().getWidth();
init();
}
private void init() {
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
private void reSize() {
LayoutParams lp = this.getLayoutParams();
//把图片的宽度设置为占满屏幕
lp.width = (int) screen_width;
//求出宽占满屏幕后与原来的倍数
Multiple = screen_width / pic_init_width;
//让图片的高度随着宽度的变化而变化,即约束比例
pic_height = pic_init_height * Multiple;
lp.height = (int) pic_height;
//最后把图片的宽高设置为ImageView的宽高即可
this.setLayoutParams(lp);
}
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
mBitmap = bm;
setup();
reSize();
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (mBitmap == null) {
return;
}
//得到图片的初始值
pic_init_height = mBitmap.getHeight();
pic_init_width = mBitmap.getWidth();
invalidate();
}
}
我说一下思路,首先得到屏幕的宽度,然后用屏幕的宽度除以图片的宽度,即可得到图片的宽度变化的倍数,然后高也要随着这个倍数变化(完成约束变化),然后把ImageView的宽高也设置为变化后图片的宽高即可,注意一点容器(容器指的是父布局,比如LinearLayout布局)的宽度设置为占满屏幕,高度要为 wrap_content, ImageView的宽高可以随便设置,因为会重新设置的,具体如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.example.k.myrecyclerview.MyImageView
android:id="@+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#9090"
/>
</LinearLayout>
我用的是RecyclerView,效果图,下面有项目地址可以参考一下:
可以看到图片是无间隔接上去的