工具篇——ScaleImageView(用于图片按比例缩放)

代码如下:

package com.wy.test.other;

import android.content.Context;

import android.util.AttributeSet;

import android.util.DisplayMetrics;

import android.util.Log;

import android.widget.ImageView;

import android.graphics.Bitmap;

import android.graphics.Canvas;

import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.Drawable;

import android.graphics.drawable.NinePatchDrawable;

import android.view.ViewGroup.LayoutParams;

/**

* 按比例缩放的ImageView

* 用于图片按比例缩放(宽度填满,高度自适应)

* 注:如果不指定宽度,则默认填满屏幕。

*/

public class ScaleImageView extends ImageView {

    public ScaleImageView(Context context) {

        super(context);

    }

    public ScaleImageView(Context context, AttributeSet attrs) {

        super(context, attrs);

    }

    public ScaleImageView(Context context, AttributeSet attrs, int defStyleAttr) {

        super(context, attrs, defStyleAttr);

    }

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        Drawable drawable = getDrawable();

        if (drawable != null) {

            int width = MeasureSpec.getSize(widthMeasureSpec);//高度根据宽度计算而得

            int height = (int) Math.ceil((float) width * (float) drawable.getIntrinsicHeight() / (float) drawable.getIntrinsicWidth());

            setMeasuredDimension(width, height);

        } else {

            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        }

    }

}

在项目中的应用:
在xml布局文件中直接使用

<com.wy.test.other.ScaleImageView

    android:layout_width="200dp"

    android:layout_height="wrap_content"

    android:src="@mipmap/ic_launcher" />

早计划,早准备,早完成。 欢迎关注!交流!Star!

GitHub:https://github.com/wangyang0313

微信公众号:一个灵活的胖子MrWang

CSDN:https://blog.csdn.net/qq941263013

20200430145304899.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,171评论 1 32
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,751评论 0 17
  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,287评论 2 54
  • 今年暑假,我随着巅峰青年汇夏令营来到慕名已久的黑山谷。 黑山谷位于重庆市万盛区,是理想的避暑圣地,...
    果果k阅读 902评论 0 1
  • 免费在线打字练习网站 网站传送门:91打字网 一、无须注册 网站无须注册,首次打字即可自动生成用户。 打开网站,就...
    binge1993阅读 17,762评论 1 15