Android 绘图进阶(四):自定义View属性(灰常重要)

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

自定义View属性

自定义View属性需要进行下面几步:
1、在res/values文件夹下创建xml文件,并编写代码
这里写图片描述

<?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"
这里写图片描述
设置背景属性后
这里写图片描述
从上图可以看出背景图片改变了,我们自定义属性设置生效了
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);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值