自定义view (二<ImageView>)

转载自:http://blog.csdn.net/lmj623565791/article/details/24300125

继续自定义View之旅,前面已经介绍过一个自定义View的基础的例子,Android 自定义View (一<文本>),如果你还对自定义View不了解可以去看看。今天给大家带来一个稍微复杂点的例子。

自定义View显示一张图片,下面包含图片的文本介绍,类似相片介绍什么的,不过不重要,主要是学习自定义View的用法么。

还记得上一篇讲的4个步骤么:

1、自定义View的属性
2、在View的构造方法中获得我们自定义的属性
[ 3、重写onMesure ]
4、重写onDraw

直接切入正题:

1、在res/values/attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="customImageText" format="string" />
    <attr name="customImageTextColor" format="color" />
    <attr name="customImageTextSize" format="dimension" />
    <attr name="customImage" format="reference" />
    <attr name="customImageScaleType">
        <enum name="fillXY" value="0" />
        <enum name="center" value="1" />
    </attr>
    <declare-styleable name="CustomImageView">
        <attr name="customImageText" />
        <attr name="customImageTextColor" />
        <attr name="customImageTextSize" />
        <attr name="customImage" />
        <attr name="customImageScaleType" />

    </declare-styleable>
</resources>
2、在构造中获得我们的自定义属性, 并且重写onmeasure(设置宽高)和ondraw(画到UI界面上)方法

package zdd.customview.hongyangview.image;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;

import zdd.customview.R;

/**
 * Created by ZDD on 2016/7/29.
 */
public class CustomImageView extends ImageView {
    // 定义与自定义属性关联的字段
    private String customText;
    private int customTextColor;
    private float customTextSize;
    private Bitmap customImage;
    private int customImageScaleType;

    // 定义画笔 文字矩形 和图形矩形
    private Paint paint;
    private Rect textRect;
    private Rect imageRect;

    // 真实的宽高
    private int width;
    private int height;

    // 样式
    private final static int IMAGE_FILLXY = 0;
    private final static int IMAGE_CENTER = 1;

    public CustomImageView(Context context) {
        this(context, null);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 获取到自定义属性值的内容
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomImageView);
        int childCount = typedArray.getIndexCount();
        for (int i = 0; i < childCount; i++) {
            int child = typedArray.getIndex(i);
            switch (child) {
                case R.styleable.CustomImageView_customImage:
                    customImage = BitmapFactory.decodeResource(getResources(), typedArray.getResourceId(child, 0));
                    break;
                case R.styleable.CustomImageView_customImageScaleType:
                    customImageScaleType = typedArray.getInt(child, 0);
                    break;
                case R.styleable.CustomImageView_customImageText:
                    customText = typedArray.getString(child);
                    break;
                case R.styleable.CustomImageView_customImageTextColor:
                    customTextColor = typedArray.getInt(child, 0);
                    break;
                case R.styleable.CustomImageView_customImageTextSize:
                    customTextSize = typedArray.getDimension(child, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
            }
        }
        typedArray.recycle();
        // 初始化画笔和文字矩形、图形矩形
        paint = new Paint();
        textRect = new Rect();
        imageRect = new Rect();
        // 设置字体大小
        paint.setTextSize(customTextSize);
        // 计算文字需要占据的范围
        paint.getTextBounds(customText, 0, customText.length(), textRect);
    }

    // 重写onMeasure设定控件的宽高
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 获取到设置的宽度类型和宽度大小
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        // 获取到设置的高度类型和宽度大小
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        /**
         * 重写之前先了解MeasureSpec的specMode,一共三种类型:
         * EXACTLY:一般是设置了明确的值或者是MATCH_PARENT
         * AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT
         * UNSPECIFIED:表示子布局想要多大就多大,很少使用*/
        // 设置宽度
        if (modeWidth == MeasureSpec.EXACTLY) {
            width = sizeWidth;
        } else {
            // 文字宽度
            int textWidht = getPaddingLeft() + textRect.width() + getPaddingRight();
            // 图片宽度
            int imageWidth = getPaddingLeft() + customImage.getWidth() + getPaddingRight();
            if (modeWidth == MeasureSpec.AT_MOST) {
                // 如果文字宽就取文字的宽度。如果图片宽就取图片的宽度
                int specWidth = Math.max(imageWidth, textWidht);
                // 如果是取到的宽度宽小就用取到的宽度,反之则用本来的宽度
                width = Math.min(specWidth, sizeWidth);
            }
        }

        // 设置高度
        if (modeHeight == MeasureSpec.EXACTLY) {
            height = sizeHeight;
        } else {
            // 获取到设置的文字和图片的总高度
            int specHeight = getPaddingTop() + textRect.height() + customImage.getHeight() + getPaddingBottom();
            if (modeHeight == MeasureSpec.AT_MOST) {
                height = Math.min(specHeight, sizeHeight);
            }
        }

        setMeasuredDimension(width, height);
    }

    // 将图片和文字绘制到控件上
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画个矩形框 (设置宽度, 颜色, 样式)
        paint.setStrokeWidth(4);
        paint.setColor(Color.RED);
        // 用这种风格进行绘制的几何图形和文本将会被用笔进行绘制,遵从在paint里设置的与stroke相关的属性(例如 setStrokeWidth()、setStrokeJoin()中所设置的属性)。
        paint.setStyle(Paint.Style.STROKE);
        // 参数 左上右下 加上画笔
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);

        // 图片文字矩形左上右下位置
        imageRect.left = getPaddingLeft();
        imageRect.top = getPaddingTop();
        imageRect.right = width - getPaddingRight();
        imageRect.bottom = height - getPaddingBottom();

        // 设置文字文字颜色样式和宽高
        paint.setColor(customTextColor);
        // 用这种风格进行绘制的几何图形和文本将会被填充,忽略了在paint里设置的与stroke相关的属性。
        paint.setStyle(Paint.Style.FILL);
        // 如果文字本身的长度超过控件的长度
        if (textRect.width() > width) {
            // 绘制文字
            TextPaint textPaint = new TextPaint(paint);
            // 如果文字的长度超过一定程度则让其显示省略号 第一个参数要输入的文字, 第二个参数文字画笔, 第三个参数文字的最长可展示长度, 第四个参数超过长度后展示省略号
            String msg = TextUtils.ellipsize(customText, textPaint, width - getPaddingLeft() - getPaddingRight(), TextUtils.TruncateAt.END).toString();
            // 将文字绘制到屏幕上(参数:1、文字内容。2、X坐标。3、Y坐标。4、画笔)
            canvas.drawText(msg, getPaddingLeft(), height - getPaddingBottom(), paint);
        } else {
            // 如果没有超过的展示方式
            canvas.drawText(customText, width / 2 - textRect.width() * 1.0f / 2, height - getPaddingBottom(), paint);
        }

        // 取消已经使用掉的块
        imageRect.bottom -= textRect.height();
        if (customImageScaleType == IMAGE_FILLXY) {
            canvas.drawBitmap(customImage, null, imageRect, paint);
        } else {
            // 如果图片是居中的情况,重新绘制图片位置
            imageRect.left = width / 2 - customImage.getWidth() / 2;
            imageRect.top = (height - textRect.height()) / 2 - customImage.getHeight() / 2;
            imageRect.right = width / 2 + customImage.getWidth() / 2;
            imageRect.bottom = (height - textRect.height()) / 2 + customImage.getHeight() / 2;
            canvas.drawBitmap(customImage, null, imageRect, paint);
        }
    }
}

下面我们引入我们的自定义View:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <zdd.customview.hongyangview.image.CustomImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        app:customImage="@mipmap/ic_launcher"
        app:customImageScaleType="center"
        app:customImageText="我"
        app:customImageTextColor="#000"
        app:customImageTextSize="12sp" />

    <zdd.customview.hongyangview.image.CustomImageView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:padding="5dp"
        app:customImage="@mipmap/ic_launcher"
        app:customImageScaleType="center"
        app:customImageText="我我萨嘎身份为打算的阿诗丹顿"
        app:customImageTextColor="#000"
        app:customImageTextSize="12sp" />

    <zdd.customview.hongyangview.image.CustomImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        app:customImage="@mipmap/ic_launcher"
        app:customImageScaleType="center"
        app:customImageText="我萨嘎身份为打算的阿诗丹顿"
        app:customImageTextColor="#000"
        app:customImageTextSize="16sp" />
</LinearLayout>

添加上我们的activity:

package zdd.customview.hongyangview.image;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import zdd.customview.R;

/**
 * Created by ZDD on 2016/7/29.
 */
public class CustomImageActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hong_yang_custom_image_view);
    }
}



我特意让显示出现3中情况:

1、字体的宽度大于图片,且View宽度设置为wrap_content

2、View宽度设置为精确值,字体的长度大于此宽度

3、图片的宽度大于字体,且View宽度设置为wrap_content

看看显示效果:


怎么样,对于这三种情况所展示的效果都还不错吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值