android自定义适配屏幕的ImageView

时间:2022-02-05 16:35:37

package org.angryfun.view;
<pre name="code" class="java">import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class FitImageView extends ImageView {
private Bitmap mBitmap;
private int mBitmapWidth;
private int mBitmapHeight;

private boolean mReady;
private boolean mSetupPending;

public FitImageView(Context context) {
super(context);
init();
}

public FitImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public FitImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

private void init() {
mReady = true;

if (mSetupPending) {
setup();
mSetupPending = false;
}
}

private void reSize() {
int width = getResources().getDisplayMetrics().widthPixels;
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.8);
int imgH = mBitmapHeight;
int imgW = mBitmapWidth;
int lastH = imgH;
int lastW = imgW;
double radio = 1.0;
radio = (width * 1.0) / imgW;
if (imgH * radio > height) {
radio = (height * 1.0) / imgH;
}
lastH = (int) (radio * imgH);
lastW = (int) (radio * imgW);
LayoutParams lp = this.getLayoutParams();
lp.width = lastW;
lp.height = lastH;
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;
}

mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();

invalidate();
}

}


 

从网络上下载后的图片加载在页面上按照ImageView自带的属性根本就设置不准确,所以自己重新封装了一个ImageView来实现屏幕自适配,其实原理就是重载 setImageBitmap函数,获得bitmap的宽度和高度然后根据手机屏幕大小自动调整ImageView控件的大小

  <org.angryfun.view.FitImageView
            android:id="@+id/img_art_real"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:layout_centerHorizontal="true" />