当前位置: 代码迷 >> 综合 >> FitWidth ImageView和TopCrop ImageView
  详细解决方案

FitWidth ImageView和TopCrop ImageView

热度:95   发布时间:2024-01-21 14:51:44.0
FitWidth ImageView: 宽度自适应

  <com.kk.drama.view.widget.FitWidthImageViewandroid:id="@+id/show_images"android:layout_width="match_parent"android:layout_height="match_parent"android:src="@drawable/default_picture" />



public class FitWidthImageView extends ImageView
{public FitWidthImageView(Context context) {super(context);setup();}public FitWidthImageView(Context context, AttributeSet attrs) {super(context, attrs);setup();}public FitWidthImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);setup();}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int width = MeasureSpec.getSize(widthMeasureSpec);int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();setMeasuredDimension(width, height);}private void setup() {setScaleType(ScaleType.CENTER_CROP);}}



TopCrop ImageView : 从头部Crop而不是center

<com.kk.drama.view.widget.FitWidthImageViewandroid:id="@+id/show_images"android:layout_width="match_parent"android:layout_height="227dp"android:src="@drawable/default_picture" />

自己改名
public class FitWidthImageView extends ImageView
{public FitWidthImageView(Context context) {super(context);setup();}public FitWidthImageView(Context context, AttributeSet attrs) {super(context, attrs);setup();}public FitWidthImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);setup();}private void setup() {setScaleType(ScaleType.CENTER_CROP);setScaleType(ScaleType.MATRIX);}@Overrideprotected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {float frameWidth = frameRight - frameLeft;float frameHeight = frameBottom - frameTop;float originalImageWidth = (float) getDrawable().getIntrinsicWidth();float originalImageHeight = (float) getDrawable().getIntrinsicHeight();float usedScaleFactor = 1;if ((frameWidth > originalImageWidth) || (frameHeight > originalImageHeight)) {// If frame is bigger than image// => Crop it, keep aspect ratio and position it at the bottom and center horizontallyfloat fitHorizontallyScaleFactor = frameWidth / originalImageWidth;float fitVerticallyScaleFactor = frameHeight / originalImageHeight;usedScaleFactor = Math.max(fitHorizontallyScaleFactor, fitVerticallyScaleFactor);}float newImageWidth = originalImageWidth * usedScaleFactor;float newImageHeight = originalImageHeight * usedScaleFactor;Matrix matrix = getImageMatrix();matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0); // Replaces the old matrix completly// matrix.postTranslate((frameWidth - newImageWidth) / 2, frameHeight - newImageHeight);//BottomCropmatrix.postTranslate((frameWidth - newImageWidth) / 2, 0);//Top CropsetImageMatrix(matrix);return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);}
}