android 随手指移动划线

本文介绍了如何在Android中通过自定义View实现手指滑动时动态绘制线条的功能,详细讲解了触控事件处理和画布操作,为开发者提供了一种在移动设备上创建交互式绘图应用的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义view

package com.example.myview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

public class DrawView extends View {
	private int x_begin;
	private int y_begin;
	private int x_end;
	private int y_end;
	private Canvas can = null;
	private Bitmap bit;
	
	
	
	public DrawView(Context  context)
	{
		super(context);
		//this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));
//		invalidate();
		bit =  Bitmap.createBitmap(880,480,Config.ARGB_8888);
		can = new Canvas();
		can.setBitmap(bit);
		
	
	}
	
	public DrawView(Context context,AttributeSet attribute)
	{
		super(context,attribute);
		bit =  Bitmap.createBitmap(481,880,Config.ARGB_8888);
		can = new Canvas();
		can.setBitmap(bit);
		
	}
	
	
	
	
	public void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
	
		canvas.drawBitmap(bit, 0, 0,null);
		
	   
//		canvas.drawCircle(x, y, 15, p);
	 //   canvas.drawLine(x_begin, y_begin, x_end, y_end, p);
	}
	
	public boolean  onTouchEvent(MotionEvent event)
	{
		
		if(event.getAction()==MotionEvent.ACTION_DOWN)
		{
	      x_begin = (int) event.getX();
	      y_begin = (int) event.getY();	
		}
		
		if(event.getAction() == MotionEvent.ACTION_MOVE)
		{
			x_end = (int)event.getX();
			y_end = (int)event.getY();
			Paint p = new Paint();
			p.setColor(Color.RED);
		
			can.drawLine(x_begin, y_begin, x_end, y_end, p);
			invalidate();
			
			x_begin = x_end;
			y_begin = y_end;
			
		   
	     }
	
		

	
		return true;
	}

}

2  xml布局

<RelativeLayout 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"
    tools:context=".MainActivity" >
    
    
        
        <com.example.myview.DrawView 
            android:id = "@+id/myview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
 

 </RelativeLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值