如何将imageview scaletype设置为topCrop

Jav*_*edi 13 android imageview scaletype

我正在编写android,我有一个imageview.我想将它的scaletype设置为topcrop.我可以在选项中找到centercrop,但这不是我的要求.我该怎么办?

Jay*_*Jay 22

自定义Android ImageView,用于包含drawable的顶部裁剪.

import android.content.Context;
import android.graphics.Matrix;
import android.widget.ImageView;

/**
* ImageView to display top-crop scale of an image view.
*
* @author Chris Arriola
*/
public class TopCropImageView extends ImageView {

public TopCropImageView(Context context) {
    super(context);
    setScaleType(ScaleType.MATRIX);
}

@Override
protected boolean setFrame(int l, int t, int r, int b) {
    final Matrix matrix = getImageMatrix();

    float scale;
    final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
    final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
    final int drawableWidth = getDrawable().getIntrinsicWidth();
    final int drawableHeight = getDrawable().getIntrinsicHeight();

    if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
        scale = (float) viewHeight / (float) drawableHeight;
    } else {
        scale = (float) viewWidth / (float) drawableWidth;
    }

    matrix.setScale(scale, scale);
    setImageMatrix(matrix);

    return super.setFrame(l, t, r, b);
}        
}
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/arriolac/3843346

  • 我叫super.setFrame(l,t,r,b); 在开头或getWidth()将返回0 (2认同)

rah*_*xyz 9

我只想要一个没有多余工作的临时解决方案.试试这个

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    android:scrollY="-100dp"
    android:id="@+id/poster"
   />
Run Code Online (Sandbox Code Playgroud)

scrollY向上或向下拉动图像.尝试使用不同的dp,你会找到合适的尺寸.

  • 虽然这可以完成手头的任务,但它不适用于不同的屏幕分辨率或父视图大小.可能不建议用于生产,因为你会在野外获得意想不到的结果.:) (3认同)