Android学习 自定义View

在Android的开发中,很多时候系统提供的View已经不能够满足我们的要求,自定义View的需求自然而然就出来了。

实现自定义的View,需要去继承View类,并重写其OnMeasure和OnDraw方法,从而实现我们自己想要的效果。

其本质上就是封装了一些自己想要的效果,并使之能够被Framework识别,跟普通的系统的控件一样,可以重复利用。

下面就拿一个例子开始吧,先上一张效果图:



在这里,有六个正方形的View,每一个View的背景颜色都不一样,图片也不一样,旋转的角度也不一样,其实这三个都是自定义的属性来的。

1. 自定义属性。

在 res/values/文件夹中创建一个 attrs.xml 文件,定义我们的属性。

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <declare-styleable name="CustomRotateView">  
  4.         <attr name="drawable" format="reference"/>  
  5.         <attr name="degree" format="float" />  
  6.         <attr name="bgcolor" format="color" />  
  7.     </declare-styleable>      
  8. </resources>  

如上 name 是属性的名字, format 是属性对应值的类型, 其中reference 表明这个值是参考其他的资源文件,在xml 中使用这个属性的形式就是:"@drawable/photo1"

2. 定义好自定义属性之后,开始创建自定义的View。

很显然,一切得从继承View开始,代码如下:

  1. package com.example.apidemostudy;  
  2.   
  3. import android.content.Context;  
  4. import android.content.res.TypedArray;  
  5. import android.graphics.Bitmap;  
  6. import android.graphics.Canvas;  
  7. import android.graphics.Color;  
  8. import android.graphics.Matrix;  
  9. import android.graphics.PixelFormat;  
  10. import android.graphics.drawable.Drawable;  
  11. import android.util.AttributeSet;  
  12. import android.util.Log;  
  13. import android.view.View;  
  14.   
  15. public class CustomRotateView extends View {  
  16.   
  17.     private final static String tag = "com.example.apidemostudy.CustomRotateView";  
  18.   
  19.     private Bitmap mBitmap; // The bitmap to be drawn  
  20.   
  21.     private int bgColor; // the BackgroundColor  
  22.   
  23.     private float degree; // the angels to rotate  
  24.   
  25.     private Matrix matrix; // the matrix to transform  
  26.   
  27.     private int mWidth = 240, mHeight = 240// The RotateImageView's height and  
  28.                                                 // width  
  29.   
  30.     private int mPivotX, mPivotY; // the pivot point to rotate by  
  31.   
  32.     private int mTranslateX, mTranslateY; // the translation to center in  
  33.                                             // current view  
  34.   
  35.     /** 
  36.      * Constructor, called when inflate the xml definition 
  37.      *  
  38.      * @param context 
  39.      * @param attrs 
  40.      */  
  41.     public CustomRotateView(Context context, AttributeSet attrs) {  
  42.         super(context, attrs);  
  43.         Log.v(tag, "CustomRotateView Initializing");  
  44.         TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.CustomRotateView);  
  45.         Drawable drawable = typedArray.getDrawable(R.styleable.CustomRotateView_drawable);        
  46.         degree = typedArray.getFloat(R.styleable.CustomRotateView_degree, 0);  
  47.         bgColor = typedArray.getColor(R.styleable.CustomRotateView_bgcolor,Color.YELLOW);  
  48.         typedArray.recycle();  
  49.   
  50.         // Change to the drawable to bitmap and zoom it until the diagnoal line  
  51.         // is shorter than the required width and height  
  52.         mBitmap = zoomBitmap(drawableToBitmap(drawable), mWidth, mHeight);  
  53.   
  54.         // Rotate axis, the central point of the bitmap  
  55.         mPivotX = mBitmap.getWidth() / 2;  
  56.         mPivotY = mBitmap.getHeight() / 2;  
  57.   
  58.         // translation, translate the bitmap to the center of this view  
  59.         mTranslateX = mWidth / 2 - mPivotX;  
  60.         mTranslateY = mHeight / 2 - mPivotY;  
  61.   
  62.         matrix = new Matrix();  
  63.     }  
  64.   
  65.     /** 
  66.      * Measure the current view set it to the fixed width and height. it's ok to 
  67.      * use the widthMeasureSpec and heightMeasureSpec if its size is decided by 
  68.      * its parent. 
  69.      */  
  70.     @Override  
  71.     public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  72.         setMeasuredDimension(mWidth, mHeight);  
  73.     }  
  74.   
  75.     /** 
  76.      * Draw the current view, 1) draw background color by bgColor 2) rotate the 
  77.      * bitmap 3) move the bitmap to center 
  78.      */  
  79.     @Override  
  80.     public void onDraw(Canvas canvas) {  
  81.   
  82.         canvas.drawColor(bgColor);  
  83.         matrix.reset();  
  84.         matrix.postRotate(degree, mPivotX, mPivotY);  
  85.         matrix.postTranslate(mTranslateX, mTranslateY);  
  86.   
  87.         canvas.drawBitmap(mBitmap, matrix, null);  
  88.   
  89.     }  
  90.   
  91.     /** 
  92.      * Zoom the bitmap to make sure it will be always displayed inside the view 
  93.      *  
  94.      * @param oldBitmap 
  95.      * @return 
  96.      */  
  97.     private Bitmap zoomBitmap(Bitmap oldBitmap, int reqWidth, int reqHeight) {  
  98.         Matrix pMatrix = new Matrix();  
  99.         int oldWidth = oldBitmap.getWidth();  
  100.         int oldHeight = oldBitmap.getHeight();  
  101.   
  102.         double diagnoal = Math.sqrt(oldWidth * oldWidth + oldHeight * oldHeight);  
  103.         float scaleX = (float) (reqWidth / diagnoal);  
  104.         float scaleY = (float) (reqHeight / diagnoal);  
  105.   
  106.         float scale = scaleX < scaleY ? scaleX : scaleY;  
  107.         pMatrix.postScale(scale, scale);  
  108.         Bitmap bitmap = Bitmap.createBitmap(oldBitmap, 00, oldWidth,  
  109.                 oldHeight, pMatrix, true);  
  110.   
  111.         return bitmap;  
  112.     }  
  113.   
  114.     /** 
  115.      * Change the drawable to Bitmap 
  116.      *  
  117.      * @param drawable 
  118.      * @return 
  119.      */  
  120.     private Bitmap drawableToBitmap(Drawable drawable) {  
  121.         int w = drawable.getIntrinsicWidth();  
  122.         int h = drawable.getIntrinsicHeight();  
  123.         Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
  124.                 : Bitmap.Config.RGB_565;  
  125.         Bitmap bitmap = Bitmap.createBitmap(w, h, config);  
  126.         Canvas canvas = new Canvas(bitmap);  
  127.         drawable.setBounds(00, w, h);  
  128.         drawable.draw(canvas);  
  129.         return bitmap;  
  130.     }  
  131.   
  132. }  


自定义的View, 有以下几个步骤:

1)构造函数 

CustomRotateView(Context context, AttributeSet attrs),从xml 中解析的view, 一定要有这个构造函数,包含有attributeSet 参数。

在构造函数中,做了几件事情:

第一,利用 TypedArray 获取自定义的属性,并将其中的drawable 转化为bitmap, 将其缩小到其对角线比当前View的宽跟高都要小,这样其在旋转角度的时候,就不会有些尖尖角角跑出这个View了。

第二,设定旋转的中心点和图片的偏移量,其实就是绕着图片中心转,然后将图片移到当前View的中心。

2)OnMeasure 函数

View 在被new 出来之后,并添加到布局去的时候,到其显示在窗口,让眼睛可以看到的过程中,其实是经过了三个步骤的,measure, layout 和 draw, 对于叶子View来说,不需要去关心layout, 因为这是由其父窗口来决定的,但是Measure过程和Draw过程,却是需要View也参与在其中的,学习Android 不久,详细的过程我目前没法很好地表达出来,各位可以自己在csdn 中找一下。

OnMeasure函数会决定当前的宽高是怎么样的,在这个例子中,简单地将当前的View 的宽高,设定为240, 240,一个正方形。

3) OnDraw 函数

当测量完当前的View 大小的时候,就是画内容了。在这里只是3.1)设置背景颜色 3.2)简单地利用matrix 作一个旋转和偏移。

3. 在布局文件中用上我们自定义的View

layout/custom_layout.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:custom="http://schemas.android.com/apk/res/com.example.apidemostudy"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent" >  
  6.   
  7.   
  8.     <com.example.apidemostudy.CustomRotateView  
  9.         android:id="@+id/rotateView1"  
  10.         android:layout_width="240dip"  
  11.         android:layout_height="300dip"  
  12.         android:layout_alignParentLeft="true"  
  13.         android:layout_alignParentTop="true"  
  14.         custom:bgcolor="#000000"  
  15.         custom:degree="0"  
  16.         custom:drawable="@drawable/photo1" />  
  17.   
  18.   
  19.     <com.example.apidemostudy.CustomRotateView  
  20.         android:id="@+id/rotateView2"  
  21.         android:layout_width="240dip"  
  22.         android:layout_height="300dip"  
  23.         android:layout_alignParentLeft="true"  
  24.         android:layout_below="@+id/rotateView1"  
  25.         custom:bgcolor="#FF0000"  
  26.         custom:degree="45"  
  27.         custom:drawable="@drawable/photo2" />  
  28.   
  29.   
  30.     <com.example.apidemostudy.CustomRotateView  
  31.         android:id="@+id/rotateView3"  
  32.         android:layout_width="240dip"  
  33.         android:layout_height="300dip"  
  34.         android:layout_alignParentLeft="true"  
  35.         android:layout_below="@+id/rotateView2"  
  36.         custom:bgcolor="#FFFF00"  
  37.         custom:degree="30"  
  38.         custom:drawable="@drawable/photo3" />  
  39.   
  40.   
  41.     <com.example.apidemostudy.CustomRotateView  
  42.         android:id="@+id/rotateView4"  
  43.         android:layout_width="240dip"  
  44.         android:layout_height="300dip"  
  45.         android:layout_alignParentRight="true"  
  46.         android:layout_alignParentTop="true"  
  47.         custom:bgcolor="#CCCCCC"  
  48.         custom:degree="60"  
  49.         custom:drawable="@drawable/photo4" />  
  50.   
  51.   
  52.     <com.example.apidemostudy.CustomRotateView  
  53.         android:id="@+id/rotateView5"  
  54.         android:layout_width="240dip"  
  55.         android:layout_height="300dip"  
  56.         android:layout_alignParentRight="true"  
  57.         android:layout_below="@+id/rotateView4"  
  58.         custom:bgcolor="#777777"  
  59.         custom:degree="-30"  
  60.         custom:drawable="@drawable/photo5" />  
  61.   
  62.   
  63.     <com.example.apidemostudy.CustomRotateView  
  64.         android:id="@+id/rotateView6"  
  65.         android:layout_width="240dip"  
  66.         android:layout_height="300dip"  
  67.         android:layout_alignParentRight="true"  
  68.         android:layout_below="@+id/rotateView5"  
  69.         custom:bgcolor="#123456"  
  70.         custom:degree="-60"  
  71.         custom:drawable="@drawable/photo6" />  
  72.   
  73.   
  74. </RelativeLayout>  
首先要定义一个自定义的命名空间,跟系统 的命名空间区分开来,如: 
  1. xmlns:custom="http://schemas.android.com/apk/res/com.example.apidemostudy"  


将上面的“Android” 字样替换成包名。

然后就是用上我们自定义的View了,用法很简单,就是直接拿着绝对路径放上去。

  1. <com.example.apidemostudy.CustomRotateView  

最后就是设置我们自定义的属性,

  1. custom:bgcolor="#000000"  
  2.  custom:degree="0"  
  3.  custom:drawable="@drawable/photo1"  


背景颜色,旋转角度 ,展示的图片。

4. 最后在Activity 中放上我们的布局文件,如下:

  1. public class CustomActivity extends Activity{  
  2.   
  3.     protected void onCreate(Bundle savedInstanceState){  
  4.       
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.custom_layout);  
  7.     }  
  8. }  


嗯,自定义View 就是这样的,大家如果有兴趣,可以看一下关于自定义的ViewGroup,位面传送门如下:

Android学习小demo(2)自定义ViewGroup




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值