码迷,mamicode.com
首页 > 其他好文 > 详细

UI复习-自定义View(触摸画圆)

时间:2014-10-29 16:56:18      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   io   color   os   ar   sp   

1>定义继承View的子类,根据业务需求重写View的方法

package com.brady.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

@SuppressLint("ClickableViewAccessibility")
public class DrawView extends View {
    
    //半径
    private int radius = 15;
    private float currentX = 25;
    private float currentY = 25;

    //创建画笔
    private Paint paint = new Paint();
    
    public DrawView(Context context) {
        super(context);
        
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        
        currentX = event.getX();
        currentY = event.getY();
        
        //使整个View实现,如果View可见,则onDraw会被调用
        //This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
        invalidate();
        
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        paint.setColor(Color.RED);
        canvas.drawCircle(currentX, currentY, radius, paint);
        super.onDraw(canvas);
    }
    
    

}

引用该子类方式:

1>直接实例化添加

2>在xml中引用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:id="@+id/root"
    tools:context="com.brady.est.MainActivity" >
    <!-- 引入自定义组件 -->
    <com.brady.view.DrawView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

 

UI复习-自定义View(触摸画圆)

标签:android   style   blog   http   io   color   os   ar   sp   

原文地址:http://www.cnblogs.com/bradylin/p/4059782.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!