学会绘制自定义的View实际上是非常重要的,在以后的实际开发中我们会有许多地方使用到我们自制的View,因此学好绘图还是很有用处的。既然我们自定义了我们的View就要学着为自定义的View设置一些属性。
  这里我们接着Android 绘图进阶(二)对我们自定义的View进行自定义它的属性。

自定义View属性

自定义View属性需要进行下面几步:
1、在res/values文件夹下创建xml文件,并编写代码
Android 绘图进阶(四):自定义View属性(灰常重要)_第1张图片

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="mybitmapview2">        <attr name="bitnapview_paintwidth" format="dimension" >attr>        <attr name="bitmapbackground"  format="reference">attr>       declare-styleable>resources>

attr:即attrbuteset(属性组合)
name:定义的view表示属性名:就好像我们使用的textsize、background、src之类的
format:format中传递类型:
dimension传递尺寸(30dp 30xp)
reference传递类似于@drawable/ic_launcher这种形式的
color传递颜色值 String传递字符串
2、在布局中添加xmlns并使用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:mybitmapview2="http://schemas.android.com/apk/res/com.example.myview"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button      android:id="@+id/btn_bitmapview2"     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="生成图片"     mybitmapview2:bitnapview_paintwidth="100dp"     /> <com.example.myview.MyBitmapView2        android:id="@+id/bitmap2"        android:layout_width="match_parent"        android:layout_height="match_parent"          mybitmapview2:bitmapbackground="@drawable/aln"      />LinearLayout>

备注:
在layout中添加xmlns,这里的mybitmapview2可以自己起名字但是在使用的时候一定要是相同的名字。比如我们修改mybitmapview2为tool那么相应的mybitmapview2:bitmapbackground="@drawable/aln"就要修改为tool:bitmapbackground="@drawable/aln"

xmlns:mybitmapview2="http://schemas.android.com/apk/res/com.example.myview"

在eclipse中xmlns的写法是上面的写法,最后是包名,但是AndroidStudio中直接写成xmlns:mybitmapview2="http://schemas.android.com/apk/res_auto"就可以了,它会自动检测
3、在自定义View中进行设置

public MyBitmapView2(Context context, AttributeSet attrs) {        super(context, attrs);        //下面一行代码是通过进入super(ctrl+左键)里找到的          final TypedArray a = context.obtainStyledAttributes(                    attrs,R.styleable.mybitmapview2);                //将drawable图片强制造型成BitmapDrawable           BitmapDrawable bitmapdraw=(BitmapDrawable) a.getDrawable(R.styleable.mybitmapview2_bitmapbackground);      if(bitmapdraw!=null){      //通过getBitmap()方法将BitmapDrawable 转成Bitmap类型          mBitmapBackground=bitmapdraw.getBitmap();      }else{          mBitmapBackground=BitmapFactory.decodeResource(getResources(), R.drawable.zly);      }          //设置圆形画笔        mpaintcircle=new Paint();        mpaintcircle.setColor(Color.YELLOW);        //设置矩形画笔的颜色        mpaintrect=new Paint();        mpaintrect.setColor(Color.GREEN);        //给画笔设置mode        PorterDuffXfermode mode=new PorterDuffXfermode(PorterDuff.Mode.XOR);            mpaintrect.setXfermode(mode);        //注:使用setStrokeCap与setStrokeJoin必须先设置style        mpaintrect.setStyle(Style.STROKE);        mpaintrect.setStrokeCap(Cap.ROUND);        mpaintrect.setStrokeJoin(Join.ROUND);        //获得布局中设置的画笔宽度属性,        //最后一个参数含义:如果没有进行设置则默认设置为30        int paintwidth=a.getDimensionPixelOffset(R.styleable.mybitmapview2_bitnapview_paintwidth, 30);        mpaintrect.setStrokeWidth(paintwidth);        mpath=new Path();        matrix=new Matrix();    }

4、效果图
没换背景前(即没设置mybitmapview2:bitmapbackground="@drawable/aln"
Android 绘图进阶(四):自定义View属性(灰常重要)_第2张图片
设置背景属性后
Android 绘图进阶(四):自定义View属性(灰常重要)_第3张图片
从上图可以看出背景图片改变了,我们自定义属性设置生效了
5、备注一下自定义View的完整代码

public class MyBitmapView2 extends View{    private int width;    private int height;    private Paint mpaintcircle;    private Paint mpaintrect;    private Bitmap mBitmap;    private Bitmap mBitmapBackground;    private Canvas BitmapCanvas;    private Bitmap back;    private Path mpath;  private  Matrix matrix;    public MyBitmapView2(Context context) {        super(context);    }    public MyBitmapView2(Context context, AttributeSet attrs) {        super(context, attrs);          final TypedArray a = context.obtainStyledAttributes(                    attrs,R.styleable.mybitmapview2);          BitmapDrawable bitmapdraw=(BitmapDrawable) a.getDrawable(R.styleable.mybitmapview2_bitmapbackground);      if(bitmapdraw!=null){          mBitmapBackground=bitmapdraw.getBitmap();      }else{          mBitmapBackground=BitmapFactory.decodeResource(getResources(), R.drawable.zly);      }          //设置圆形画笔        mpaintcircle=new Paint();        mpaintcircle.setColor(Color.YELLOW);        //设置矩形画笔的颜色        mpaintrect=new Paint();        mpaintrect.setColor(Color.GREEN);        //给画笔设置mode        PorterDuffXfermode mode=new PorterDuffXfermode(PorterDuff.Mode.XOR);            mpaintrect.setXfermode(mode);        //注:使用setStrokeCap与setStrokeJoin必须先设置style        mpaintrect.setStyle(Style.STROKE);        mpaintrect.setStrokeCap(Cap.ROUND);        mpaintrect.setStrokeJoin(Join.ROUND);        int paintwidth=a.getDimensionPixelOffset(R.styleable.mybitmapview2_bitnapview_paintwidth, 30);        mpaintrect.setStrokeWidth(paintwidth);        mpath=new Path();        matrix=new Matrix();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //,new Matrix().postScale((float)mBitmapBackground.getWidth()/width,(float) mBitmapBackground.getHeight()/height)        //画布的背景色      //  canvas.drawBitmap(mBitmapBackground,new Rect(0,0, back.getWidth(), back.getHeight()),new Rect(0,0, width, height), null);         Log.d("放缩", (float)width/mBitmapBackground.getWidth()+"");         Log.d("gao", ""+(float)height/mBitmapBackground.getHeight());        canvas.drawBitmap(mBitmapBackground, matrix, null);        //在bitmap图的画布上绘制圆形与矩形       // BitmapCanvas.drawCircle(width/2, height/2, width/2, mpaintcircle);//dst        BitmapCanvas.drawRect(0, 0, width, height, mpaintcircle);//src        BitmapCanvas.drawPath(mpath, mpaintrect);        //将bitmap图片绘制到画布上面        canvas.drawBitmap(mBitmap, 0, 0, null);    }    private float x;    private float y;    private float old_x;    private float old_y;    @Override    public boolean onTouchEvent(MotionEvent event) {        switch (event.getAction()) {        case MotionEvent.ACTION_DOWN:{            x=event.getX();            y=event.getY();        //mpath.addCircle(x, y, 50, Direction.CW);            mpath.moveTo(x, y);            invalidate();            old_x=x;            old_y=y;            return true;        }               case MotionEvent.ACTION_MOVE:               x=event.getX();            y=event.getY();            mpath.moveTo(old_x,old_y);            mpath.lineTo(x,y);            //mpath.rQuadTo((x+old_x)/2,(y+old_y), x, y);            invalidate();            old_x=x;            old_y=y;            return true;                    default:            break;        }        return super.onTouchEvent(event);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);        height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);        setMeasuredDimension(width, height);        mBitmap=Bitmap.createBitmap(width, height, Config.ARGB_8888);        //创建Bitmap图的画布        BitmapCanvas=new Canvas(mBitmap);         back=Bitmap.createBitmap(width, height, Config.ARGB_8888);         matrix.reset();         matrix.postScale((width+0.0f)/mBitmapBackground.getWidth(), (height+0.0f)/mBitmapBackground.getHeight());//      Canvas canva=new Canvas(mBitmapBackground);//      canva.drawBitmap(mBitmapBackground,  new Rect(0,0,mBitmapBackground.getWidth(),mBitmapBackground.getHeight()), new Rect(0,0,width,height), null);    }}

更多相关文章

  1. activity 的属性android:taskAffinity和android:allowTaskRepare
  2. Android中你也许不知道的线性布局Layout_weight属性权重比例分配
  3. Android进阶之_实现滑动的7种方式详解
  4. Android UI组件进阶(1)——带进度条的按钮
  5. android UI进阶之可延伸的图像
  6. Android进阶——Android控制端连接同一网段Wi-Fi家用打印机小结
  7. Android实现自定义View的自定义属性的一般步骤

随机推荐

  1. 【Android】如何用MediaPlayer实现一个简
  2. Android学习笔记(9)---FrameLayout中上下层
  3. android bluetooth 移植相关注意事项
  4. android之launcher时序图and图标的建立
  5. Android(安卓)ConstraintLayout 约束布局
  6. Android(安卓)旋转屏幕捕获当前屏幕的状
  7. Android(安卓)重力感应获取手机运动方向
  8. Android(安卓)中与 Touch 事件分发和消费
  9. 一个Demo让你掌握所有的android控件
  10. Android中各种形状