可以设置宽高比,宽度确定,高度比例缩放的ImageView快速实现

在开发中经常碰到这样一种情况:要求图片不能变形,宽度为设备屏幕宽度,高度与宽度比例为0.77,因为安卓设备特别杂,所以不能写死,只能动态的匹配.今天就给你一个自定义的ImageView,来彻底解决这个问题,而实现起来是非常简单的

1.自定义控件ZRationImageview的class文件

package com.z.zviewlib;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;

/**
 * Created by Miller Zhang  on 2017/2/22.
 * desc:
 * github:https://github.com/zxyaust  CSDN:http://blog.csdn.net/qq_31340657
 * Whatever happens tomorrow,we've had today.
 */

public class ZRationImageView extends ImageView {

    private float ration;

    public ZRationImageView(Context context) {
        this(context, null);
    }

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

    public ZRationImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ZRationImageView);
        ration = array.getFloat(R.styleable.ZRationImageView_ration, 0f);
        array.recycle();
        setScaleType(ScaleType.FIT_XY);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int width = this.getWidth();
        int height = (int) (width * ration);
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        setLayoutParams(layoutParams);
    }
}

2.自定义属性

 <declare-styleable name="ZRationImageView">
        <attr name="ration" format="float"></attr>
    </declare-styleable>

3.使用

<com.z.zviewlib.ZRationImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:ration="1"
        android:src="@mipmap/ic_launcher" />

大功告成了,你可以设置不同的ration值,试试看,完全没问题.你可以设置src,也可以用background,

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值