Android实现固定比例的ImageView

来源:互联网 发布:商业数据分析与挖掘 编辑:程序博客网 时间:2024/05/22 10:30

自定义imageview,其中的ratio属性代表宽是高的几倍,在xml中用:

app:ratio="1.5"

表示该图片宽是高的1.5倍

public class RatioImageView extends ImageView {    /**     * 宽高比例     */    private float mRatio = 0f;    public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    public RatioImageView(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RatioImageView);        mRatio = typedArray.getFloat(R.styleable.RatioImageView_ratio, 0f);        typedArray.recycle();    }    public RatioImageView(Context context) {        super(context);    }    /**     * 设置ImageView的宽高比     *     * @param ratio     */    public void setRatio(float ratio) {        mRatio = ratio;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int width = MeasureSpec.getSize(widthMeasureSpec);        if (mRatio != 0) {            float height = width / mRatio;            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) height, MeasureSpec.EXACTLY);        }        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                Drawable drawable = getDrawable();                if (drawable != null) {                    drawable.mutate().setColorFilter(Color.GRAY,                            PorterDuff.Mode.MULTIPLY);                }                break;            case MotionEvent.ACTION_MOVE:                break;            case MotionEvent.ACTION_CANCEL:            case MotionEvent.ACTION_UP:                Drawable drawableUp = getDrawable();                if (drawableUp != null) {                    drawableUp.mutate().clearColorFilter();                }                break;        }        return super.onTouchEvent(event);    }}

在styles.xml中加入以下代码

    <declare-styleable name="RatioImageView">        <attr name="ratio" format="float"/>    </declare-styleable>
阅读全文
0 0
原创粉丝点击