Created
April 19, 2014 07:36
-
-
Save holmeszyx/11077012 to your computer and use it in GitHub Desktop.
FixImageView 自动调整等比高宽
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.example.imagetext.view; | |
| import android.content.Context; | |
| import android.graphics.drawable.Drawable; | |
| import android.util.AttributeSet; | |
| import android.widget.ImageView; | |
| public class FixImageView extends ImageView{ | |
| private int mFixWidth = -1; | |
| public FixImageView(Context context, AttributeSet attrs, int defStyle) { | |
| super(context, attrs, defStyle); | |
| // TODO Auto-generated constructor stub | |
| init(); | |
| } | |
| public FixImageView(Context context, AttributeSet attrs) { | |
| super(context, attrs); | |
| // TODO Auto-generated constructor stub | |
| init(); | |
| } | |
| public FixImageView(Context context) { | |
| super(context); | |
| // TODO Auto-generated constructor stub | |
| init(); | |
| } | |
| private void init(){ | |
| } | |
| @Override | |
| protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
| // It is Auto-generated method stub | |
| if (mFixWidth > 0){ | |
| widthMeasureSpec = MeasureSpec.makeMeasureSpec(mFixWidth, MeasureSpec.EXACTLY); | |
| setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); | |
| return; | |
| } | |
| super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
| } | |
| @Override | |
| public void setImageDrawable(Drawable drawable) { | |
| // It is Auto-generated method stub | |
| float height = getHeight(); | |
| mFixWidth = (int) ((height / drawable.getIntrinsicHeight()) * drawable.getIntrinsicWidth()); | |
| System.out.println(String.format("h:%f, fixw: %d, dh: %d, dw: %d", height, mFixWidth, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight())); | |
| requestLayout(); | |
| super.setImageDrawable(drawable); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment