解决imageviw(图片)固定比例问题
思路:首先定义可以固定比例的FrameLayout,然后将ImageView放在自定义的FrameLayout上。
第一步:在values目录下建立attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="FixedScaleLayout">
<attr name="scale" format="float" />
</declare-styleable>
</resources>
第二步:
package com.yinongjing.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;
import com.yinongjing.xmqx.R;
public class FixedScaeLayout extends FrameLayout {
private float scale = 1;
public FixedScaeLayout(Context context) {
this(context, null);
}
public FixedScaeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FixedScaeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.FixedScaleLayout, 0, 0);
try {
scale = a.getFloat(R.styleable.FixedScaleLayout_scale, 1);//获取比例
} finally {
a.recycle();
}
Log.i("logutils", "scale" + scale);
}
public void setScale(float scale){
this.scale=scale;
}
// 设置比例
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) (scale * width);//设置高度
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, mode);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eeeeee" >
<com.yinongjing.widget.FixedScaeLayout
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="2"
app:scale="0.5" >
<ImageView
android:id="@+id/ivShowImg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/img_search_fail" />
</com.yinongjing.widget.FixedScaeLayout>
</RelativeLayout>