Android自定义View:利用onMeasure精准控制图片和半圆尺寸

在Android开发中,自定义View是实现个性化UI的重要途径。而onMeasure()方法作为View绘制流程中的关键一环,决定了View的尺寸测量,合理利用它可以实现对View尺寸的精准控制。本文将通过两个实例,详细讲解如何利用onMeasure()方法固定图片控件尺寸以及根据MeasureSpec模式动态调整半圆大小。

一、 固定图片控件尺寸

需求:创建一个自定义ImageView,确保图片大小固定,不受布局文件中宽高设置的影响。

思路:

  1. 创建一个继承自ImageView的自定义类FixedSizeImageView。2. 重写onMeasure()方法,获取图片的原始宽高。3. 使用setMeasuredDimension()方法将测量结果设置为图片的原始宽高。

**代码示例:**javapublic class FixedSizeImageView extends ImageView {

// ...构造方法省略

@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // 获取图片的宽度和高度        Drawable drawable = getDrawable();        int width = drawable.getIntrinsicWidth();        int height = drawable.getIntrinsicHeight();

    // 设置固定的图片宽度和高度        setMeasuredDimension(width, height);    }}

**布局文件使用:**xml<com.example.FixedSizeImageView android:layout_width='200dp' android:layout_height='200dp' android:src='@drawable/my_image' />

即使在布局文件中设置了不同的宽高,FixedSizeImageView依然会按照图片的原始尺寸显示。

二、 根据MeasureSpec模式动态调整半圆大小

需求:创建一个自定义View,绘制一个半圆,并根据MeasureSpec的模式(AT_MOSTEXACTLY)动态调整半圆大小。

思路:

  1. 创建一个继承自View的自定义类HalfCircleView。2. 在onMeasure()方法中,根据MeasureSpec的模式设置半圆的半径: - EXACTLY模式:半径为父容器剩余宽高的一半。 - AT_MOST模式:半径固定为300。3. 在onDraw()方法中,使用canvas.drawArc()方法绘制半圆。

**代码示例:**javapublic class HalfCircleView extends View {

private Paint paint;    private int radius;

// ...构造方法及初始化省略

@Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    // 根据测量模式设置半径        if (widthMode == MeasureSpec.EXACTLY) {            radius = widthSize / 2;        } else if (widthMode == MeasureSpec.AT_MOST) {            radius = 300;        }

    if (heightMode == MeasureSpec.EXACTLY) {            radius = Math.min(radius, heightSize / 2);        } else if (heightMode == MeasureSpec.AT_MOST) {            radius = Math.min(radius, 300);        }

    // 设置View的实际宽高        int width = radius * 2;        int height = radius;        setMeasuredDimension(width, height);    }

@Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        // 绘制半圆        canvas.drawArc(0, 0, radius * 2, radius * 2, 180, 180, true, paint);
Android自定义View:利用onMeasure精准控制图片和半圆尺寸

原文地址: https://www.cveoy.top/t/topic/Q1j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录