自定义控件二

1.attrs.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <declare-styleable name="RectImageView">
        <attr name="ratio" format="float"/>
        <attr name="ratioX" format="float"/>
        <attr name="ratioY" format="float"/>
    </declare-styleable>
    
    <attr name="wide" format="float"></attr>
    <attr name="height" format="float"></attr>
    <attr name="titletextcolor" format="color"></attr>
    <attr name="titletextsize" format="dimension"></attr>
    <attr name="titletext" format="string"></attr>
    <attr name="imageSrc" format="reference"></attr>
    <attr name="imageScaleType">
        <enum name="fillxy" value="0"/>
        <enum name="center" value="1"/>
    </attr>
    
    <!-- 自定义view二 -->
    <declare-styleable name="SecondView">
         <attr name="titletextcolor" />
         <attr name="titletextsize" />
         <attr name="titletext" />
         <attr name="imageSrc"></attr>
         <attr name="imageScaleType"></attr>
    </declare-styleable>
</resources>


2.布局文件中的调用  

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:tw="http://schemas.android.com/apk/res/com.example.textmyview"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

 <!-- 这里的tw:titletextsize 就是自定义的属性 -->

    <com.example.textmyview.myview.SecondView
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:padding="10dp"
        tw:imageScaleType="center"
        tw:imageSrc="@drawable/ic_launcher"
        tw:titletext="不理我了asdfasdfasdf"
        tw:titletextcolor="@color/trans_pop_blue"
        tw:titletextsize="20dp" />
    
    <com.example.textmyview.myview.SecondView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        tw:titletextcolor="@color/trans_pop_blue"
        tw:titletextsize="17dp"
        tw:titletext="真是看起来有点厉害的样子"
        tw:imageSrc="@drawable/ic_launcher"
        tw:imageScaleType="center"/>
    
    <com.example.textmyview.myview.SecondView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        tw:titletextcolor="@color/trans_pop_blue"
        tw:titletextsize="17dp"
        tw:titletext="眼睛"
        tw:imageSrc="@drawable/abc"
        tw:imageScaleType="center"/>

</LinearLayout>
</ScrollView>

3.SecondView类的内容

package com.example.textmyview.myview;

import com.example.textmyview.R;

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.Paint.Style;
import android.graphics.Rect;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

public class SecondView extends View{
	private static final int IMAGE_FITXY=0;//与控件适配
	
	private String titleStr;//字  字符串
	private int titleSize;//字体大小
	private int titleColor;//字体颜色
	private int imageScaleType;//图片的显示格式
	private int imageSrc;//图片的路径
	private int mWide;//view的宽度
	private int mHeight;//view的高度
	
	private Bitmap mImageView;//图片对象
	private Paint mPaint;//画笔对象
	private Rect rect;//图片要的显示矩形
	private Rect textRect;//字要显示的矩形

	public SecondView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}
	
	public SecondView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}
	
	public SecondView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		TypedArray a =context.getTheme().obtainStyledAttributes(attrs, R.styleable.SecondView, defStyleAttr, 0);
		int count =a.getIndexCount();
		for (int i = 0; i < count; i++) {
			switch (a.getIndex(i)) {
			case R.styleable.SecondView_titletext:
				titleStr=a.getString(a.getIndex(i));
				break;
			case R.styleable.SecondView_titletextcolor:
				titleColor=a.getColor(a.getIndex(i), Color.BLUE);			
				break;
			case R.styleable.SecondView_titletextsize:
				titleSize=a.getDimensionPixelSize(a.getIndex(i), (int)TypedValue.applyDimension(
						TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
				break;
			case R.styleable.SecondView_imageSrc:
				imageSrc=a.getResourceId(a.getIndex(i), 0);
				mImageView=BitmapFactory.decodeResource(getResources(), imageSrc);
				break;
			case R.styleable.SecondView_imageScaleType:
				imageScaleType=a.getInt(a.getIndex(i), 0);
				break;

			default:
				break;
			}
		}
		a.recycle();
		mPaint=new Paint();
		rect=new Rect();
		textRect=new Rect();
		mPaint.setTextSize(titleSize);
		mPaint.getTextBounds(titleStr, 0, titleStr.length(), textRect);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int wideMode=MeasureSpec.getMode(widthMeasureSpec);
		int wideSize=MeasureSpec.getSize(widthMeasureSpec);
		int heightMode=MeasureSpec.getMode(heightMeasureSpec);
		int heightSize=MeasureSpec.getSize(heightMeasureSpec);
		if(wideMode==MeasureSpec.EXACTLY){
			mWide=wideSize;
		}else{
			int imageWide=getPaddingLeft()+getPaddingRight()+mImageView.getWidth();
			int textWide=getPaddingLeft()+getPaddingRight()+textRect.width();
			int maxWide=Math.max(imageWide, textWide);
			if(wideMode==MeasureSpec.AT_MOST){//父组件能够给出的最大空间
				int minWide=Math.min(wideSize, maxWide);//取父控件能给的最大宽度  和  子控件宽度的  最小值
				mWide=minWide;
			}else{
				mWide=maxWide;
			}
		}
		
		if(heightMode==MeasureSpec.EXACTLY){
			mHeight=heightSize;
		}else{
			int height=getPaddingBottom()+getPaddingTop()+mImageView.getHeight()+textRect.height();
			if(heightMode==MeasureSpec.AT_MOST){
				mHeight=Math.min(heightSize, height);
			}else{
				mHeight=height;
			}
		}
		setMeasuredDimension(mWide, mHeight);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		//画整个控件的外圈
		mPaint.setStrokeWidth(4);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setColor(Color.BLUE);
		canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
		
		//写图片下面的字
		mPaint.setColor(titleColor);
		mPaint.setStyle(Style.FILL);
		//判断字的长度是否比控件的长度要长
		if((mWide)<textRect.width()){
			/**
			 * android:ellipsize="end"     省略号在结尾
			   android:ellipsize="start"   省略号在开头
               android:ellipsize="middle"   省略号在中间
               android:ellipsize="marquee"  跑马灯
                                   其中的四个参数,第一个是字符串  第二个是  textpaint对象  第三个是可显示长度,第四个省略号的位置
			 */
			TextPaint paint=new TextPaint(mPaint);
			String msg=TextUtils.ellipsize(titleStr, paint, 
					(float)(mWide-getPaddingLeft()-getPaddingRight()), TextUtils.TruncateAt.END).toString();
			canvas.drawText(msg, getPaddingLeft(), mHeight-getPaddingBottom(), mPaint);
		}else{
			canvas.drawText(titleStr, mWide/2-textRect.width()* 1.0f/2, mHeight-getPaddingBottom(), mPaint);
		}
		
		//画图片
		if(imageScaleType==IMAGE_FITXY){//判断是否是图片匹配整个矩形的大小
			rect.right=mWide-getPaddingRight();
			rect.left=getPaddingLeft();
			rect.bottom=mHeight-getPaddingBottom()-textRect.height();
			rect.top=getPaddingTop();
			canvas.drawBitmap(mImageView, null, rect, mPaint);
		}else{//居中
			rect.right=mWide/2+mImageView.getWidth()/2;
			rect.left=mWide/2-mImageView.getWidth()/2;
			rect.bottom=(mHeight-textRect.height())/2+mImageView.getHeight()/2;
			rect.top=(mHeight-textRect.height())/2-mImageView.getHeight()/2;
			canvas.drawBitmap(mImageView, null, rect, mPaint);
		}
	}
}

以下是显示结果



以下是参考的文章  http://blog.csdn.net/lmj623565791/article/details/24300125


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值