GVKun编程网logo

android – 使用Rebound库为Facebook Messanger聊天头添加自然拖动效果到ImageView

26

本文将分享android–使用Rebound库为FacebookMessanger聊天头添加自然拖动效果到ImageView的详细内容,此外,我们还将为大家带来关于androidBoundServic

本文将分享android – 使用Rebound库为Facebook Messanger聊天头添加自然拖动效果到ImageView的详细内容,此外,我们还将为大家带来关于android Bound Service使用:使用Message类绑定服务、Android DragImageView实现下拉拖动图片放大效果、Android ImageView setImageBitmap 不显示图片、Android ImageView 的 scaleType 属性与 adjustViewBounds 属性的相关知识,希望对你有所帮助。

本文目录一览:

android – 使用Rebound库为Facebook Messanger聊天头添加自然拖动效果到ImageView

android – 使用Rebound库为Facebook Messanger聊天头添加自然拖动效果到ImageView

我正在开发一个应用程序,我在Activity中拖动我的ImageView.
我为弹簧动画配置了Facebook Rebound library,最初用于Facebook Messenger的聊天头动画.我想在拖动它时将这种动画添加到我的ImageView中.
  VIDEO

到目前为止,当我触摸ImageView(在rootview上实现spring)时,我能够获得弹簧动画,这是我的代码.如何将这种自然类型的拖动效果实现到我的ImageView.

public class MainTry extends Activity {

    int windowwidth;
    int windowheight;

    private LayoutParams layoutParams;
    private final BaseSpringSystem mSpringSystem = SpringSystem.create();
    private FrameLayout mRootView;
    private Spring spring;
    private View mImageView;
    private VeLocityTracker veLocity = null;
    private float dx;
    private float dy;
    private View rootView;
    private ImageView img;

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    // Create a system to run the physics loop for a set of springs.
    SpringSystem springSystem = SpringSystem.create();

    // Add a spring to the system.
    spring = springSystem.createSpring();

    rootView = getwindow().getDecorView()
            .findViewById(android.R.id.content);

    windowwidth = getwindowManager().getDefaultdisplay().getWidth();
    windowheight = getwindowManager().getDefaultdisplay().getHeight();
    img = (ImageView) findViewById(R.id.imageView2);

    rootView.setonTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // spring.setEndValue(1);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // spring.setEndValue(0);
                break;
            }
            return true;
        }
    });
    // Add a listener to observe the motion of the spring.
    spring.addListener(new SimpleSpringListener() {

        @Override
        public void onspringUpdate(Spring spring) {
            // You can observe the updates in the spring
            // state by asking its current value in onspringUpdate.
            float value = (float) spring.getCurrentValue();
            float scale = .5f - (value * 0.1f);
            img.setScaleX(scale);
            img.setScaleY(scale);
        }
    });
    // spring.setEndValue(1);

    img.setonTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            LayoutParams layoutParams = (LayoutParams) img
                    .getLayoutParams();

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dx = event.getRawX() - 10;
                dy = event.getRawY() - 10;

                if (veLocity == null) {
                    // Retrieve a new VeLocityTracker object to watch the
                    // veLocity of a motion.
                    veLocity = VeLocityTracker.obtain();
                } else {
                    // Reset the veLocity tracker back to its initial state.
                    veLocity.clear();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                dx = event.getRawX() - 10;
                dy = event.getRawY() - 10;


                veLocity.addMovement(event);
                spring.setVeLocity(veLocity.getYVeLocity());
                spring.setCurrentValue(dy);
                spring.setEndValue(dy);


                layoutParams.leftMargin = (int) dx - 10;
                layoutParams.topMargin = (int) dy - 10;
                img.setLayoutParams(layoutParams);
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_UP:
                veLocity.addMovement(event);
                spring.setVeLocity(veLocity.getYVeLocity());
                spring.setCurrentValue(event.getRawY() - 10);
                spring.setEndValue(0);

                break;

            default:
                break;
            }
            return true;
        }
    });

}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void onPause() {
    super.onPause();
}


}

解决方法:

那这个呢:

class V extends View implements SpringListener {
    private static final int NUM_ELEMS = 4;
    private Spring[] mXSprings = new Spring[NUM_ELEMS];
    private Spring[] mYSprings = new Spring[NUM_ELEMS];
    private Paint mPaint = new Paint();
    private Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    public V(Context context) {
        super(context);
        SpringSystem ss = SpringSystem.create();

        Spring s;
        for (int i = 0; i < NUM_ELEMS; i++) {
            s = ss.createSpring();
            s.setSpringConfig(new MySpringConfig(200, i == 0? 8 : 15 + i * 2, i, true));
            s.addListener(this);
            mXSprings[i] = s;

            s = ss.createSpring();
            s.setSpringConfig(new MySpringConfig(200, i == 0? 8 : 15 + i * 2, i, false));
            s.addListener(this);
            mYSprings[i] = s;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        mXSprings[0].setCurrentValue(w / 2);
        mYSprings[0].setCurrentValue(0);

        mXSprings[0].setEndValue(w / 2);
        mYSprings[0].setEndValue(h / 2);
    }

    @Override
    public void onspringActivate(Spring s) {
    }

    @Override
    public void onspringAtRest(Spring s) {
    }

    @Override
    public void onspringEndStateChange(Spring s) {
    }

    @Override
    public void onspringUpdate(Spring s) {
        MySpringConfig cfg = (MySpringConfig) s.getSpringConfig();
        if (cfg.index < NUM_ELEMS - 1) {
            Spring[] springs = cfg.horizontal? mXSprings : mYSprings;
            springs[cfg.index + 1].setEndValue(s.getCurrentValue());
        }
        if (cfg.index == 0) {
            invalidate();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mXSprings[0].setEndValue(event.getX());
        mYSprings[0].setEndValue(event.getY());
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        for (int i = NUM_ELEMS - 1; i >= 0; i--) {
            mPaint.setAlpha(i == 0? 255 : 192 - i * 128 / NUM_ELEMS);
            canvas.drawBitmap(mBitmap, 
                    (float) mXSprings[i].getCurrentValue() - mBitmap.getWidth() / 2,
                    (float) mYSprings[i].getCurrentValue() - mBitmap.getHeight() / 2,
                    mPaint);
        }
    }

    class MySpringConfig extends SpringConfig {
        int index;
        boolean horizontal;
        public MySpringConfig(double tension, double friction, int index, boolean horizontal) {
            super(tension, friction);
            this.index = index;
            this.horizontal = horizontal;
        }
    }
}

android Bound Service使用:使用Message类绑定服务

android Bound Service使用:使用Message类绑定服务

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <Button android:id="@+id/current_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="当前时间"
        android:textColor="@android:color/white"
        android:textSize="25dp"/>

</RelativeLayout>

CurrentTimeService1.java

package com.example.demoboundservice;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.format.Time;
import android.widget.Toast;

public class CurrentTimeService1 extends Service{
	
	public static final int CURRENT_TIME=0;
	
	private class IncomingHandler extends Handler{
		public void handleMessage(Message msg){
			if(msg.what==CURRENT_TIME){
				Time time = new Time();
				time.setToNow();
				String currentTime = time.format("%Y-%m-%d %H:%M:%S");
				Toast.makeText(CurrentTimeService1.this,currentTime,Toast.LENGTH_LONG).show();
			}else{
				super.handleMessage(msg);
			}
		}
	}
	

	
	public IBinder onBind(Intent intent){

		Messenger messenger = new Messenger(new IncomingHandler());
		return messenger.getBinder();
	}
	
}

CurrentTimeActivity.java:

package com.example.demoboundservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;

public class CurrentTimeActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	
	Messenger messenger;
	boolean bound;
	
	protected void onStart(){
		super.onStart();
		Button button = (Button)findViewById(R.id.current_time);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {

				Intent intent = new Intent(CurrentTimeActivity.this,CurrentTimeService.class);
				bindService(intent,connection,BIND_AUTO_CREATE);
				if(bound){
					Message message = Message.obtain(null,CurrentTimeService1.CURRENT_TIME,0,0);
					try{
						messenger.send(message);
					}catch(RemoteException e){
						e.printStackTrace();
					}
				}
			}
		});
	}
	
	
	protected void onStop(){
		super.onStop();
		if(bound){
			bound  = false;
			unbindService(connection);
		}
	}
	
	private ServiceConnection connection = new ServiceConnection(){
		public void onServiceDisconnected(ComponentName name){
			messenger = null;
			bound = false;
		}
		public void onServiceConnected(ComponentName name,IBinder service){
			messenger = new Messenger(service);
			bound = true;
		}
	};

}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demoboundservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.demoboundservice.CurrentTimeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name="com.example.demoboundservice.CurrentTimeService1"/>
    </application>

</manifest>


Android DragImageView实现下拉拖动图片放大效果

Android DragImageView实现下拉拖动图片放大效果

DragImageView下拉拖动图片放大,先上图:

主要的类:继承了RelativeLayout,再在RelativeLayout里面添加ImageView,通过Touch事件来改变ImageView的缩放,缩放时计算scale,使其在手指移动到屏幕底部时,图片底部也刚好到达屏幕底部,手指松开时,图片逐步回弹。

package com.example.dragimagescale; 
 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Matrix; 
import android.graphics.PointF; 
import android.os.Handler; 
import android.os.Message; 
import android.util.AttributeSet; 
import android.util.displayMetrics; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.WindowManager; 
import android.widget.ImageView; 
import android.widget.ImageView.ScaleType; 
import android.widget.RelativeLayout; 
 
public class DragScaleImageView extends RelativeLayout { 
 private String TAG = "DragScaleImageView"; 
 private static final int BACK_SCALE = 1010; 
 
 private Context mContext; 
 private AttributeSet attrs; 
 private int displayWidth = 0; 
 private int displayHeight = 0; 
 private int mImageId; 
 private Bitmap bmp; 
 private ImageView imageView; 
 
 /** 是否处在回弹状态 */ 
 private boolean isbacking = false; 
 
 /** 用于记录拖拉图片移动的坐标位置 */ 
 private Matrix matrix = new Matrix(); 
 /** 用于记录图片要进行拖拉时候的坐标位置 */ 
 private Matrix currentMatrix = new Matrix(); 
 private Matrix defaultMatrix = new Matrix(); 
 /** 图片的宽高 */ 
 private float imgHeight,imgWidth; 
 /** 初始状态 */ 
 private int mode = 0; 
 /** 拖拉照片模式 */ 
 private final int MODE_DRAG = 1; 
 
 private float scaleY = 0; 
 
 /** 用于记录开始时候的坐标位置 */ 
 private PointF startPoint = new PointF(); 
 
 /** 用于记录开始时候的在整个屏幕中的Y坐标位置 */ 
 private float startRawY = 0; 
 float scale = 1; 
    
 private TouchEventListener touchEventListener = null; 
 private BackScaleListener backScaleListener = null; 
 
 public DragScaleImageView(Context context,AttributeSet attrs) { 
  super(context,attrs); 
  // Todo Auto-generated constructor stub 
  this.mContext = context; 
  this.attrs = attrs; 
  initView(); 
 } 
 
 public DragScaleImageView(Context context) { 
  super(context); 
  // Todo Auto-generated constructor stub 
  this.mContext = context; 
  initView(); 
 } 
 
 public DragScaleImageView(Activity activity,Bitmap resBitmap,int width,int height) { 
  super(activity); 
 } 
 
 /** 
  * 初始化图片 
  */ 
 private void initView() { 
  /* 取得屏幕分辨率大小 */ 
  displayMetrics dm = new displayMetrics(); 
  WindowManager mWm = (WindowManager) mContext 
    .getSystemService(Context.WINDOW_SERVICE); 
  mWm.getDefaultdisplay().getMetrics(dm); 
  displayWidth = dm.widthPixels; 
  displayHeight = dm.heightPixels; 
 
  TypedArray a = mContext.obtainStyledAttributes(attrs,R.styleable.DragScaleImageView); 
  mImageId = a.getResourceId(R.styleable.DragScaleImageView_scale_image,0); 
  a.recycle(); 
  if (null == bmp && mImageId != 0) { 
   bmp = BitmapFactory.decodeResource(getResources(),mImageId); 
   float scale = (float) displayWidth / (float) bmp.getWidth();// 1080/1800 
   matrix.postScale(scale,scale,0); 
   imgHeight = scale * bmp.getHeight(); 
   imgWidth = scale * bmp.getWidth(); 
  } else { 
   imgHeight = displayWidth; 
   imgWidth = displayWidth; 
  } 
  initimageView(); 
 } 
 
 private void initimageView() { 
  imageView = new ImageView(mContext); 
  imageView.setimageMatrix(matrix); 
  defaultMatrix.set(matrix); 
  Log.w(TAG,"imgWidth :" + imgWidth); 
  Log.w(TAG,"imgHeight :" + imgHeight); 
 
  RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( 
    (int) imgWidth,(int) imgHeight); 
  imageView.setLayoutParams(layoutParams); 
  imageView.setimageBitmap(bmp); 
  imageView.setScaleType(ScaleType.CENTER_CROP); 
  this.addView(imageView); 
 } 
 
 /** 
  * 设置ImageView的宽高 
  * 
  * @param width 
  * @param height 
  */ 
 public void setimageWidthAndHeight(int width,int height) { 
  imgWidth = width; 
  imgHeight = height; 
  RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( 
    (int) imgWidth,(int) imgHeight); 
  imageView.setLayoutParams(layoutParams); 
 } 
 
 public boolean onTouchEvent(MotionEvent event) { 
  Log.w(TAG,"onTouchEvent :" + event.getAction()); 
  // 当该View放置在ScrollView里面时,会与父控件Touch事件冲突,所以touch该控件区域时,父控件不可用 
  if (event.getAction() == MotionEvent.ACTION_UP) { 
   getParent().requestdisallowInterceptTouchEvent(false); 
  } else { 
   getParent().requestdisallowInterceptTouchEvent(true);// true表示父类的不可用; 
  } 
  switch (event.getAction() & MotionEvent.ACTION_MASK) { 
  // 手指压下屏幕 
  case MotionEvent.ACTION_DOWN: 
   if (isbacking) { 
    return super.onTouchEvent(event); 
   } 
   int[] location = new int[2]; 
   imageView.getLocationInWindow(location); 
   if (location[1] >= 0) { 
    mode = MODE_DRAG; 
    // 记录ImageView当前的移动位置 
    currentMatrix.set(imageView.getimageMatrix()); 
    startPoint.set(event.getX(),event.getY()); 
    startRawY = event.getRawY(); 
    Log.w(TAG,"onTouchEvent startRawY:" + startRawY); 
   } 
   break; 
  // 手指在屏幕上移动,改事件会被不断触发 
  case MotionEvent.ACTION_MOVE: 
   // 拖拉图片 
   if (mode == MODE_DRAG) { 
//    float dx = event.getX() - startPoint.x; // 得到x轴的移动距离 
    float dy = event.getY() - startPoint.y; // 得到y轴的移动距离 
    // 在没有移动之前的位置上进行移动 
    if (dy > 0) { 
     matrix.set(currentMatrix); 
     Log.w(TAG,"onTouchEvent dy:" + dy); 
     scale = ((dy / (displayHeight - startRawY) * (displayHeight - imgHeight)) + imgHeight) 
       / imgHeight; // 得到缩放倍数,当手指移动到屏幕底部时,图片也达到屏幕底部 
     Log.w(TAG,"onTouchEvent scale:" + scale); 
     
     scaleY = dy; 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) (scale * imgWidth),(int) (scale * imgHeight)); 
     imageView.setLayoutParams(relativeLayout); 
     matrix.postScale(scale,imgWidth / 2,0); 
     imageView.setimageMatrix(matrix); 
    } 
   } 
   break; 
  // 手指离开屏幕 
  case MotionEvent.ACTION_UP: 
   // 当触点离开屏幕,图片还原 
   mHandler.sendEmptyMessage(BACK_SCALE); 
  case MotionEvent.ACTION_POINTER_UP: 
   // 当两个手指移动时,取消移动图片 
   mode = 0; 
   break; 
  } 
  // 设置的Touch监听事件 
  if (touchEventListener != null) { 
   touchEventListener.onTouchEvent(event); 
  } 
  return true; 
 } 
  
 /** 逐步回弹 */ 
 @SuppressLint("HandlerLeak") 
 private Handler mHandler = new Handler() { 
  @Override 
  public void handleMessage(Message msg) { 
   // Todo Auto-generated method stub 
   switch (msg.what) { 
   case BACK_SCALE: 
    scale = (scaleY / 2 + imgHeight) / (imgHeight);// 得到缩放倍数 
    if (scaleY > 0) { 
     isbacking = true; 
     matrix.set(currentMatrix); 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) (scale * imgWidth),0); 
     imageView.setimageMatrix(matrix); 
     scaleY = (float) (scaleY / 2 - 1); 
     mHandler.sendEmptyMessageDelayed(BACK_SCALE,20);// 逐步回弹 
    } else { 
     scaleY = 0; 
     RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams( 
       (int) imgWidth,(int) imgHeight); 
     imageView.setLayoutParams(relativeLayout); 
     matrix.set(defaultMatrix); 
     imageView.setimageMatrix(matrix); 
     isbacking = false; 
    } 
    if (backScaleListener != null) { 
     backScaleListener.onBackScale(); 
    } 
    break; 
   default: 
    break; 
   } 
   super.handleMessage(msg); 
  } 
 }; 
  
 public void setTouchEventListener(TouchEventListener touchEventListener) { 
  this.touchEventListener = touchEventListener; 
 } 
  
 public void setBackScaleListener(BackScaleListener backScaleListener) { 
  this.backScaleListener = backScaleListener; 
 } 
 
 /** Touch事件监听 */ 
 public interface TouchEventListener { 
  public void onTouchEvent(MotionEvent event); 
 } 
 /** 回弹事件监听 */ 
 public interface BackScaleListener { 
  public void onBackScale(); 
 } 
} 

调用的Activity:

package com.example.dragimagescale; 
 
import com.example.dragimagescale.DragScaleImageView.BackScaleListener; 
import com.example.dragimagescale.DragScaleImageView.TouchEventListener; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.MotionEvent; 
 
public class MainActivity extends Activity { 
 
  
 DragScaleImageView mDragScaleImageView; 
  
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
 
  mDragScaleImageView = (DragScaleImageView) findViewById(R.id.dragScaleImageView); 
  /** 自定义ImageView的宽高,若不设置则按图片宽高压缩至屏幕宽度 */ 
//  mDragScaleImageView.setimageWidthAndHeight(720,300); 
  // Touch事件监听 
  mDragScaleImageView.setTouchEventListener(new TouchEventListener() { 
    
   @Override 
   public void onTouchEvent(MotionEvent event) { 
    // Todo Auto-generated method stub 
    // do something here 
   } 
  }); 
  // 回弹事件监听 
  mDragScaleImageView.setBackScaleListener(new BackScaleListener() { 
    
   @Override 
   public void onBackScale() { 
    // Todo Auto-generated method stub 
    // do something here 
   } 
  }); 
 } 
 
  
  
  
 
} 

xml 布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 xmlns:dragscaleimageview="http://schemas.android.com/apk/res/com.example.dragimagescale" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:background="#ffffff" > 
 
 <com.example.dragimagescale.DragScaleImageView 
  android:id="@+id/dragScaleImageView" 
  android:layout_width="match_parent"   
  android:layout_height="wrap_content" 
  dragscaleimageview:scale_image="@drawable/image" 
  > 
 </com.example.dragimagescale.DragScaleImageView> 
 
</RelativeLayout> 

下载:源码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

Android ImageView setImageBitmap 不显示图片

Android ImageView setImageBitmap 不显示图片

从sd卡里读出图片后有时调用setImageBitmap(bitmap)方法会显示不出图片,仔细考虑过后原来是加载的图片过大导致的,解决办法为:

BitmapFactory.Options op = new BitmapFactory.Options();

op.inSampleSize = 2;

//op.inJustDecodeBounds = true; //它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。            

//op.inPreferredConfig = Bitmap.Config.ARGB_4444;    // 默认是Bitmap.Config.ARGB_8888



private Bitmap createBitmapFromByteData(byte[] data ,Options options){
        
        Bitmap bitmap = null;
        if(options == null){
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        }else{
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        }
        return bitmap;
}

这样返回的bitmap就可以被显示出来了。

Android ImageView 的 scaleType 属性与 adjustViewBounds 属性

Android ImageView 的 scaleType 属性与 adjustViewBounds 属性

ImageView 的 scaleType 的属性有好几种,分别是 matrix(默认)、center、centerCrop、centerInside、fitCenter、fitEnd、fitStart、fitXY

android:scaleType="center"

保持原图的大小,显示在 ImageView 的中心。当原图的 size 大于 ImageView 的 size,超过部分裁剪处理。

android:scaleType="centerCrop"

以填满整个 ImageView 为目的,将原图的中心对准 ImageView 的中心,等比例放大原图,直到填满 ImageView 为止(指的是 ImageView 的宽和高都要填满),原图超过 ImageView 的部分作裁剪处理。

android:scaleType="centerInside"

以原图完全显示为目的,将图片的内容完整居中显示,通过按比例缩小原图的 size 宽 (高) 等于或小于 ImageView 的宽 (高)。如果原图的 size 本身就小于 ImageView 的 size,则原图的 size 不作任何处理,居中显示在 ImageView。

android:scaleType="matrix"

不改变原图的大小,从 ImageView 的左上角开始绘制原图,原图超过 ImageView 的部分作裁剪处理。

android:scaleType="fitCenter"

把原图按比例扩大或缩小到 ImageView 的 ImageView 的高度,居中显示

android:scaleType="fitEnd"

把原图按比例扩大 (缩小) 到 ImageView 的高度,显示在 ImageView 的下部分位置

android:scaleType="fitStart"

把原图按比例扩大 (缩小) 到 ImageView 的高度,显示在 ImageView 的上部分位置

android:scaleType="fitXY"

把原图按照指定的大小在 View 中显示,拉伸显示图片,不保持原比例,填满 ImageView.

下面附上效果图:

原图为 Pocoyo 的头像,上图为原图的 size 大于 ImageView 的 size,下图为原图的 size 小于 ImageView 的 size

Android <wbr>ImageView的scaleType属性与adjustViewBounds属性[转]

Tip:很多人都觉得 fitCenter 和 centerInside 没有区别,根据上面的效果图来分析,其实是有区别的。fitCenter 是将原图等比例放大或缩小,使原图的高度等于 ImageView 的高度,并居中显示,而 centerInside 在原图的原本 size 大于 ImageView 的 size 时,则缩小原图,效果同 fitCenter;在原图的原本 size 小于 ImageView 的 size 时,则不进行任何 size 处理,居中显示,效果同 center。


 

ImageView 的 android:adjustViewBounds 属性为是否保持原图的长宽比,单独设置不起作用,需要配合 maxWidth 或 maxHeight 一起使用(该句话的后半句我还没有去验证,但我用的时候没有与 maxWidth、MaxHeight 一起使用)。


今天的关于android – 使用Rebound库为Facebook Messanger聊天头添加自然拖动效果到ImageView的分享已经结束,谢谢您的关注,如果想了解更多关于android Bound Service使用:使用Message类绑定服务、Android DragImageView实现下拉拖动图片放大效果、Android ImageView setImageBitmap 不显示图片、Android ImageView 的 scaleType 属性与 adjustViewBounds 属性的相关知识,请在本站进行查询。

本文标签: