android 帶圖片的文字框

來源:互聯網
上載者:User

基本原理

自訂一個IconTextView類繼承自TextView,添加iconsrc屬性,表示圖片。

重新onDraw方法,將圖片繪製到textVIew前面,然後將textView右移。

廢話不多說了,直接代碼就明白。

package com.zb;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Rect;import android.graphics.drawable.BitmapDrawable;import android.util.AttributeSet;import android.view.View;import android.widget.TextView;public class IconTextView extends TextView {private final String nameSpace="http://com.zb.text";//儲存映像資源ID的變數private int resourceId=0;private Bitmap bitmap;public IconTextView(Context context, AttributeSet attrs) {super(context, attrs);resourceId=attrs.getAttributeResourceValue(nameSpace, "iconSrc", 0);//擷取映像資源的值if(resourceId!=0)bitmap=BitmapFactory.decodeResource(getResources(), resourceId);}@Overrideprotected void onDraw(Canvas canvas) {if(bitmap!=null){Rect src=new Rect();//原圖地區Rect target=new Rect();//目的地區域src.left=0;src.top=0;src.right=bitmap.getWidth();src.bottom=bitmap.getHeight();int textHeight=(int) getTextSize();target.left=0;//計算映像複製地區的縱座標,target.top=(int) (((getMeasuredHeight()-getTextSize())/2)+1);target.bottom=target.top+textHeight;target.right=(int) (textHeight*((float)bitmap.getWidth()/bitmap.getHeight()));//繪製canvas.drawBitmap(bitmap, src, target, getPaint());//向右移動TextView的的距離canvas.translate(target.right+2,0);}super.onDraw(canvas);}}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:zb="http://com.zb.text"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <com.zb.IconTextView        android:id="@+id/iconText1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        zb:iconSrc="@drawable/small"        android:text="妞給爺笑一個" />        <com.zb.IconTextView        android:id="@+id/iconText1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        zb:iconSrc="@drawable/small"        android:textSize="30dp"        android:text="妞給爺笑一個" /></LinearLayout>
代碼很簡單把。
布局檔案
這裡需要幾個地方,namespace xmlns:zb="http://com.zb.text"要和代碼裡面定義的一樣。
ok!!
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.