安卓自定义ImageView,实现宽高比为1(正方形图片)

说明:
在安卓中,ImageView的高和宽通过onMeasure方法来控制,我们只需要自定义一个View继承自ImageView并重写该方法即可。

package com.example.myapplication1.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

public class widthEqualsHeightImageView extends AppCompatImageView {

    public widthEqualsHeightImageView(Context context) {
        super(context);
    }

    public widthEqualsHeightImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public widthEqualsHeightImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

我们将宽高相应的尺寸参数都传入宽的尺寸参数,就可以实现啦。

全部评论

相关推荐

点赞 评论 收藏
分享
回家当保安:复旦✌🏻,佬你的简历感觉挺好的,寒假日常hc比较少。佬可以过完年之后再试试,日常实习hc比较充足
点赞 评论 收藏
分享
12-24 20:52
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务