自定义设置图像比例

解决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>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值