自定義imageview 實現(xiàn)按照圖片比例加載圖片


import?android.content.Context;

import?android.graphics.Canvas;

import?android.graphics.drawable.Drawable;

import?android.util.AttributeSet;

import?android.widget.ImageView;

public?classSubjectImageViewextendsImageView{

publicSubjectImageView(Contextcontext,AttributeSetattrs)?{

super(context,attrs);

//TODOAuto-generated?constructor?stub

????}


@Override

protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec)?{

//獲取真實的圖片

Drawabledrawable=getDrawable();


if(drawable!=null){

//獲取真實的寬

intwidth=drawable.getMinimumWidth();

//獲取真實的高?

intheight=drawable.getMinimumHeight();

//計算寬和高的比例?

floatscale=?(float)width/height;

//獲取測量寬的規(guī)則

intwithsize=MeasureSpec.getSize(widthMeasureSpec);

//按照比例計算高的測量規(guī)則?

intheightsize=?(int)?(withsize/scale);

//設置高的測量規(guī)則?第一個值是按照比例計算的高?第二個參數(shù)是測量模式?精確

heightMeasureSpec=MeasureSpec.makeMeasureSpec(heightsize,MeasureSpec.EXACTLY);


????????}



super.onMeasure(widthMeasureSpec,heightMeasureSpec);

????}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容