Android 图形处理

一、理论概述

1、什么Graphics?

手机上显示的任何界面, 无论是文字,按钮或图片, 都是系统内置的一些API绘制的Graphics(图形,图像)

Graphics分为2D和3D两种, 我们这里不去管3D Graphics

在我们应用中操作最多的Graphics就是图片, 如何操作图片是我们要学习的重点

如何利用系统的相关API绘制一个自定义的Graphics也是我们将要去

2、相关API

(1)Bitmap:  

位图,图片在内存中数据对象  .bmp .jpg .png

(2)Drawable:

就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是一个图层(LayerDrawable)我们根据画图的需求,创建相应的可画对象

(3)Canvas:

画布,手机屏幕上用于绘图的目标区域

(4)Paint:

我们可以把它看做一个画图工具,比如画笔、画刷。他管理了每个画图工具的字体、颜色、样式。

(5)Matrix:

矩阵,高等数学里有介绍,在图像处理方面,主要是用于平面的缩放、平移、旋转等操作

 

二、图形处理之图片的读取与保存

1、基础

(1)加载图片得到bitmap对象

BitmapFactory.decodeResource(Resources res, int id)

BitmapFactory.decodeFile(String pathName)

(2)将bitmap对象保存到SD

compress(CompressFormat format, int quality, OutputStream stream)

(3)SD卡操作权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

/*
 Bitmap: 加载一张图片数据到内存中, 都可以封装成一个Bitmap对象
    需求1: 加载资源文件中的图片资源并显示
    需求2: 加载存储空间中的图片资源并显示
    需求3: 将一个bitmap对象保存到存储空间中
 */
public class MainActivity extends Activity{

    private ImageView iv_bitmap1;
    private ImageView iv_bitmap2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_bitmap1=findViewById(R.id.iv_bitmap1);
        iv_bitmap2=findViewById(R.id.iv_bitmap2);
        //需求1: 加载资源文件中的图片资源并显示
        iv_bitmap1.setImageResource(R.drawable.ic_launcher);
        //需求2: 加载存储空间中的图片资源并显示
        Bitmap bitmap= null;
        try {
            bitmap = BitmapFactory.decodeStream(openFileInput("ic_launcher.png"));
            iv_bitmap2.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        iv_bitmap2.setImageBitmap(bitmap);
    }

    public void saveImage(View v) throws IOException {
        //需求3: 将一个bitmap对象保存到存储空间中
        //读取assets下的图片ic_launcher.png
        InputStream is=getAssets().open("ic_launcher.png");
        Bitmap bitmap=BitmapFactory.decodeStream(is);
        //压缩存储
        bitmap.compress(Bitmap.CompressFormat.PNG,100,openFileOutput("ic_launcher.png", Context.MODE_PRIVATE));
        Toast.makeText(this, "保存完成", Toast.LENGTH_SHORT).show();
    }

}
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="vertical" >

      <Button
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="保存图片"
          android:onClick="saveImage"/>

      <ImageView
          android:id="@+id/iv_bitmap1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" />

      <ImageView
          android:id="@+id/iv_bitmap2"
          android:layout_width="150dp"
          android:layout_height="150dp" />

   </LinearLayout>

 

三、图形处理之图片的缩放/旋转/平移处理

1、图片的缩放/旋转/平移处理

在Android中, 可以通过Matrix来对图片进行缩放,旋转和平移的操作

Matrix: 矩阵(高数), 在图像处理方面,主要是用于平面的缩放、平移、旋转等操作

相关API:

Matrix.postScale(float sx, float sy) : 缩放

Matrix.postRotate(float degrees) : 旋转

Matrix.postTranslate(float dx, float dy) : 平移

Matrix.reset() : 清空重置

ImageView.setImageMatrix(Matrix matrix) 设置图片的Matrix

/*
   Matrix ,中文里叫矩阵,高等数学里有介绍,在图像处理方面,主要是用于平面的缩放、平移、旋转等操作

 */
public class MainActivity extends Activity{

    private EditText et_matrix_scale;
    private EditText et_matrix_rotate;
    private EditText et_matrix_translateX;//偏移量X
    private EditText et_matrix_translateY;//偏移量Y

    private ImageView iv_matrix_icon;

    private Matrix matrix;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_matrix_scale = (EditText) findViewById(R.id.et_matrix_scale);
        et_matrix_rotate = (EditText) findViewById(R.id.et_matrix_rotate);
        et_matrix_translateX = (EditText) findViewById(R.id.et_matrix_translateX);
        et_matrix_translateY = (EditText) findViewById(R.id.et_matrix_translateY);

        iv_matrix_icon = (ImageView) findViewById(R.id.iv_matrix_icon);

        matrix=new Matrix();
    }

    public void scaleBitmap(View view) {
        float scale= Float.parseFloat(et_matrix_scale.getText().toString());
        //保存缩放比例
        matrix.postScale(scale,scale);
        //将matrix设置到imageView
        iv_matrix_icon.setImageMatrix(matrix);
    }

    public void rotateBitmap(View view) {
        float degree = Float.parseFloat(et_matrix_rotate.getText().toString());
        //保存旋转角度
        matrix.postRotate(degree);
        //将matrix设置到imageView
        iv_matrix_icon.setImageMatrix(matrix);
    }

    public void translateBitmap(View view) {
        float dx = Float.parseFloat(et_matrix_translateX.getText().toString());
        float dy = Float.parseFloat(et_matrix_translateY.getText().toString());
        //保存平移数据
        matrix.postTranslate(dx, dy);
        //将matrix设置到imageView
        iv_matrix_icon.setImageMatrix(matrix);
    }

    public void clearMatrix(View view) {
        matrix.reset();
        //将matrix设置到imageView
        iv_matrix_icon.setImageMatrix(matrix);
    }


}

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:padding="10dp">
      <LinearLayout
          android:layout_marginTop="10dip"
          android:layout_width="fill_parent"
          android:layout_height="50dip"
          android:orientation="horizontal">
         <EditText android:id="@+id/et_matrix_scale"
             android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:hint="缩放比例"
             android:text="0.25"/>
         <EditText android:id="@+id/et_matrix_rotate"
             android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="30"
             android:hint="旋转角度"
             android:onClick="rotateBitmap"/>
         <EditText android:id="@+id/et_matrix_translateX"
             android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="10"
             android:hint="X偏移"/>
         <EditText android:id="@+id/et_matrix_translateY"
             android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="10"
             android:hint="y偏移"/>
      </LinearLayout>

      <LinearLayout android:layout_marginTop="10dip"
          android:layout_width="fill_parent"
          android:layout_height="50dip"
          android:orientation="horizontal">
         <Button android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="缩放"
             android:onClick="scaleBitmap"/>
         <Button android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="旋转"
             android:onClick="rotateBitmap"/>
         <Button android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="移动"
             android:onClick="translateBitmap"/>
         <Button android:layout_weight="1.0"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="还原"
             android:onClick="clearMatrix"/>
      </LinearLayout>

      <ImageView android:id="@+id/iv_matrix_icon"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:src="@drawable/ic_launcher"
          android:scaleType="matrix"/>

   </LinearLayout>

 

四、图形处理之Shape图形图片

在Android中, 可以通过<shap>来配置自定义图形, 这一技术在应用中比较常用

 

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:padding="10dp">

      <Button
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:background="@drawable/shape_test"
          android:text="使用Shape做的按钮" />

   </LinearLayout>

 

shape_test.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 圆角 -->
    <corners
        android:radius="8dp">
    </corners>

    <!-- 描边 -->
    <stroke
        android:dashGap="2dp"
        android:dashWidth="10dp"
        android:width="4dp"
        android:color="#00ff00">
    </stroke>
    <!-- 尺寸 -->
    <size
        android:width="120dp"
        android:height="40dp">
    </size>
    <!-- 内部单色填充 -->
    <solid android:color="#ff0000">
    </solid>
    <!-- 内部渐变色填充 -->
    <gradient
        android:centerColor="#ffffff"
        android:endColor="#ffff00"
        android:startColor="#0000ff"
        android:angle="90">
    </gradient>

</shape>

 

五、图形处理之Selector多状态图片

一、Selector多状态图片

selector多状态图形在可以在正常,按下,选中等状态下显示不同的图形, 在应用中十分常用

在使用时可以把它的xml文件看作一个图片

它可以与图片或<shap>一起使用

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:padding="10dp">

      <ImageView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center_horizontal"
          android:background="@drawable/select_drawble"
          android:onClick="clickIV" />

   </LinearLayout>
select_drawble.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 按下的图片 (必须写在前面)-->
    <item android:state_pressed="true" android:drawable="@drawable/main_index_search_pressed"></item>
    <!-- 正常情况下的图片 -->
    <item android:drawable="@drawable/main_index_search_normal"></item>

</selector>

 

六、图形处理之Selector+shape做按钮

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:padding="10dp">

      <Button
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:background="@drawable/selector_shape"
          android:text="使用Selector+Shape做的按钮" />
   </LinearLayout>

 

selector_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true">
        <shape>
            <corners android:radius="5dp"/>
            <solid android:color="#ff0000"/>
            <padding android:top="5dp" android:bottom="5dp"/>
        </shape>
    </item>
    <item>
        <shape>
            <corners android:radius="10dp"/>
            <solid android:color="#00ff00"/>
            <padding android:top="5dp" android:bottom="5dp"/>
        </shape>
    </item>
</selector>

 

七、图形处理之9patch图片(.9.png) 

一、9patch图片(.9.png) 

.9.png图片是一种特别的png图片, 它在放大显示时不会失真

.9.png图片可以分为三种类型区域

(1)正中间区域: 可向水平和垂直方向复制扩展

(2)中上, 中下, 中左与中右区域: 只能向一个方向扩展

(3)四个角区域: 大小不会变化

 

八、图形处理之绘制自定义图形

一、绘制自定义图形

ShapeDrawable之OvalShape、RectShape、PaintDrawable、ArcShape

OvalShape:椭圆形形状

RectShape:矩形形状

PaintDrawable:一个继承自ShapeDrawable更为通用、可以直接使用的形状

ArcShape:扇形、扇面形状,顺时针,开始角度30, 扫描的弧度跨度180

public class DrawTestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    class MyView extends View {

        private ShapeDrawable shapeDrawable;
        private Paint paint;

        public MyView(Context context) {
            super(context);
            shapeDrawable = new ShapeDrawable(new OvalShape());
            shapeDrawable.getPaint().setColor(Color.RED);//指定颜色
            shapeDrawable.setBounds(10, 10, 200, 100);//指定位置

            paint = new Paint();
            paint.setColor(Color.BLUE); //颜色
            paint.setTextSize(20);//字体大小
            paint.setTypeface(Typeface.DEFAULT_BOLD);//粗体字
            paint.setAntiAlias(true);//消除锯齿
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            //画绿色背景
            canvas.drawColor(Color.GREEN);
            //画椭圆
            shapeDrawable.draw(canvas);//将自己画到画布上
            //画文本
            canvas.drawText("andrlid hello world", 10, 120, paint);
        }
    }
}

 

 

 

一、基本几何图形绘制

1、Paint与Canvas

Paint就像是平时用的笔,可以设置颜色,粗细,大小,透明度,字体,填充样式都是用画笔设置的。

Canvas像是平时用的纸,可以绘制直线,点,矩形,圆形,圆弧等。

 

2、Paint的基本设置函数、

  • paint.setAntiAlias(true);//抗锯齿功能
  • paint.setColor(Color.RED);  //设置画笔颜色    
  • paint.setStyle(Style.FILL);//设置填充样式
  • paint.setStrokeWidth(30);//设置画笔宽度
  • paint.setShadowLayer(10, 15, 15, Color.GREEN);//设置阴影
     

void setStyle (Paint.Style style)     设置填充样式

Paint.Style.FILL    :填充内部
Paint.Style.FILL_AND_STROKE  :填充内部和描边
Paint.Style.STROKE  :仅描边

 

setShadowLayer (float radius, float dx, float dy, int color)    添加阴影

参数:

radius:阴影的倾斜度
dx:水平位移
dy:垂直位移

paint.setShadowLayer(10, 15, 15, Color.GREEN);//设置阴影

3、Canvas的基本设置:

画布背景设置:

  • canvas.drawColor(Color.BLUE);
  • canvas.drawRGB(255, 255, 0);   //这两个功能一样,都是用来设置背景颜色的。

 

实例:继承View然后重写onDraw(),绘图就在onDraw()里面就可以了

//重写OnDraw()函数,在每次重绘时自主实现绘图
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		
		//设置画笔基本属性
		Paint paint=new Paint();
		paint.setAntiAlias(true);//抗锯齿功能
		paint.setColor(Color.RED);  //设置画笔颜色    
		paint.setStyle(Style.FILL);//设置填充样式   Style.FILL/Style.FILL_AND_STROKE/Style.STROKE
		paint.setStrokeWidth(5);//设置画笔宽度
		paint.setShadowLayer(10, 15, 15, Color.GREEN);//设置阴影
		
		//设置画布背景颜色     
        canvas.drawRGB(255, 255,255);
		
        //画圆
        canvas.drawCircle(190, 200, 150, paint);	
	}

 

4、基本几何图形绘制

(1)画直线

void drawLine (float startX, float startY, float stopX, float stopY, Paint paint)

参数:

startX:开始点X坐标
startY:开始点Y坐标
stopX:结束点X坐标
stopY:结束点Y坐标

Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.FILL);//设置填充样式 
paint.setStrokeWidth(5);//设置画笔宽度
 
canvas.drawLine(100, 100, 200, 200, paint);

(2)多条直线

void drawLines (float[] pts, Paint paint)
void drawLines (float[] pts, int offset, int count, Paint paint)

参数:

pts:是点的集合,大家下面可以看到,这里不是形成连接线,而是每两个点形成一条直线,pts的组织方式为{x1,y1,x2,y2,x3,y3,……}


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.FILL);//设置填充样式 
paint.setStrokeWidth(5);//设置画笔宽度
 
float []pts={10,10,100,100,200,200,400,400};
canvas.drawLines(pts, paint);

上面有四个点:(10,10)、(100,100),(200,200),(400,400)),两两连成一条直线

(3)

void drawPoint (float x, float y, Paint paint)

参数:
float X:点的X坐标
float Y:点的Y坐标

Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.FILL);//设置填充样式 
paint.setStrokeWidth(15);//设置画笔宽度
 
canvas.drawPoint(100, 100, paint);

 

(4)多个点

void drawPoints (float[] pts, Paint paint)
void drawPoints (float[] pts, int offset, int count, Paint paint)

参数:
float[] pts:点的合集,与上面直线一直,样式为{x1,y1,x2,y2,x3,y3,……}
int offset:集合中跳过的数值个数,注意不是点的个数!一个点是两个数值;
count:参与绘制的数值的个数,指pts[]里人数值个数,而不是点的个数,因为一个点是两个数值
 


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.FILL);//设置填充样式 
paint.setStrokeWidth(15);//设置画笔宽度
 
float []pts={10,10,100,100,200,200,400,400};
canvas.drawPoints(pts, 2, 4, paint);
(同样是上面的四个点:(10,10)、(100,100),(200,200),(400,400),drawPoints里路过前两个数值,即第一个点横纵坐标,画出后面四个数值代表的点,即第二,第三个点,第四个点没画;效果图如下)

 

(5)矩形工具类RectF与Rect

RectF(float left, float top, float right, float bottom)

Rect和RectF用法一样。

(6)矩形

void drawRect (float left, float top, float right, float bottom, Paint paint)
void drawRect (RectF rect, Paint paint)
void drawRect (Rect r, Paint paint)
 


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.FILL);//设置填充样式 
paint.setStrokeWidth(15);//设置画笔宽度
 
canvas.drawRect(10, 10, 100, 100, paint);//直接构造
 
RectF rect = new RectF(120, 10, 210, 100);
canvas.drawRect(rect, paint);//使用RectF构造
 
Rect rect2 =  new Rect(230, 10, 320, 100); 
canvas.drawRect(rect2, paint);//使用Rect构造

(7)圆角矩形

void drawRoundRect (RectF rect, float rx, float ry, Paint paint)

参数:
RectF rect:要画的矩形
float rx:生成圆角的椭圆的X轴半径
float ry:生成圆角的椭圆的Y轴半径

 

(8)、圆形

void drawCircle (float cx, float cy, float radius, Paint paint)

参数:
float cx:圆心点X轴坐标 
float cy:圆心点Y轴坐标
float radius:圆的半径

圆心坐标确定园的位置。

 

(9)、椭圆

椭圆是根据矩形生成的,以矩形的长为椭圆的X轴,矩形的宽为椭圆的Y轴,建立的椭圆图形

void drawOval (RectF oval, Paint paint)

参数:
RectF oval:用来生成椭圆的矩形

 

(10)弧

弧是椭圆的一部分,而椭圆是根据矩形来生成的,所以弧当然也是根据矩形来生成的;

void drawArc (RectF oval, float startAngle, float sweepAngle, boolean useCenter, Paint paint)

参数:
RectF oval:生成椭圆的矩形
float startAngle:弧开始的角度,以X轴正方向为0度
float sweepAngle:弧持续的角度
boolean useCenter:是否有弧的两边,True,还两边,就是弧闭合,False,只有一条弧
 

 

一、路径及文字

canvas中绘制路径利用:void drawPath (Path path, Paint paint)

1、直线路径

void moveTo (float x1, float y1):直线起点

void lineTo (float x2, float y2):直线结束点又是下一条直线的起点,可以多次使用。

void close ():如果连续画了几条直线,但没有形成闭环,调用Close()会将路径首尾点连接起来


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.STROKE);//填充样式改为描边 
paint.setStrokeWidth(5);//设置画笔宽度
 
Path path = new Path();
 
path.moveTo(10, 10); //设定起始点
path.lineTo(10, 100);//第一条直线的终点,也是第二条直线的起点
path.lineTo(300, 100);//画第二条直线
path.lineTo(500, 100);//第三条直线
path.close();//闭环
 
canvas.drawPath(path, paint)

 

2、矩形路径
void addRect (float left, float top, float right, float bottom, Path.Direction dir)
void addRect (RectF rect, Path.Direction dir)

这里Path类创建矩形路径的参数与上篇canvas绘制矩形差不多,唯一不同的一点是增加了Path.Direction参数;
Path.Direction有两个值:
Path.Direction.CCW:是counter-clockwise缩写,指创建逆时针方向的矩形路径;
Path.Direction.CW:是clockwise的缩写,指创建顺时针方向的矩形路径;


//先创建两个大小一样的路径
//第一个逆向生成
Path CCWRectpath = new Path();
RectF rect1 =  new RectF(50, 50, 240, 200);
CCWRectpath.addRect(rect1, Direction.CCW);
 
//第二个顺向生成
Path CWRectpath = new Path();
RectF rect2 =  new RectF(290, 50, 480, 200);
CWRectpath.addRect(rect2, Direction.CW);
 
//先画出这两个路径 
canvas.drawPath(CCWRectpath, paint);
canvas.drawPath(CWRectpath, paint);

 

沿着路径绘制文字


//先创建两个大小一样的路径
//第一个逆向生成
Path CCWRectpath = new Path();
RectF rect1 =  new RectF(50, 50, 240, 200);
CCWRectpath.addRect(rect1, Direction.CCW);
 
//第二个顺向生成
Path CWRectpath = new Path();
RectF rect2 =  new RectF(290, 50, 480, 200);
CWRectpath.addRect(rect2, Direction.CW);
 
//先画出这两个路径 
canvas.drawPath(CCWRectpath, paint);
canvas.drawPath(CWRectpath, paint);
 
//依据路径写出文字
String text="风萧萧兮易水寒,壮士一去兮不复返";
paint.setColor(Color.GRAY);
paint.setTextSize(35);
canvas.drawTextOnPath(text, CCWRectpath, 0, 18, paint);//逆时针生成
canvas.drawTextOnPath(text, CWRectpath, 0, 18, paint);//顺时针生成

 

3、圆角矩形路径
void addRoundRect (RectF rect, float[] radii, Path.Direction dir)
void addRoundRect (RectF rect, float rx, float ry, Path.Direction dir)

这里有两个构造函数,部分参数说明如下:
第一个构造函数:可以定制每个角的圆角大小:
float[] radii:必须传入8个数值,分四组,分别对应每个角所使用的椭圆的横轴半径和纵轴半径,如{x1,y1,x2,y2,x3,y3,x4,y4},其中,x1,y1对应第一个角的(左上角)用来产生圆角的椭圆的横轴半径和纵轴半径,其它类推……
第二个构造函数:只能构建统一圆角大小
float rx:所产生圆角的椭圆的横轴半径;
float ry:所产生圆角的椭圆的纵轴半径;
 

Path path = new Path();
RectF rect1 =  new RectF(50, 50, 240, 200);
path.addRoundRect(rect1, 10, 15 , Direction.CCW);
 
RectF rect2 =  new RectF(290, 50, 480, 200);
float radii[] ={10,15,20,25,30,35,40,45};
path.addRoundRect(rect2, radii, Direction.CCW);
 
canvas.drawPath(path, paint);

4、圆形路径

void addCircle (float x, float y, float radius, Path.Direction dir)

参数说明:
float x:圆心X轴坐标 
float y:圆心Y轴坐标
float radius:圆半径

Path path = new Path();
path.addCircle(200, 200, 100, Direction.CCW);
canvas.drawPath(path, paint);

5、椭圆路径

void addOval (RectF oval, Path.Direction dir)

参数说明:
RectF oval:生成椭圆所对应的矩形
Path.Direction :生成方式,与矩形一样,分为顺时针与逆时针,意义完全相同,不再重复


Path path = new Path();
RectF rect =  new RectF(50, 50, 240, 200);
path.addOval(rect, Direction.CCW);
canvas.drawPath(path, paint);

6、弧形路径
void addArc (RectF oval, float startAngle, float sweepAngle)

参数:
RectF oval:弧是椭圆的一部分,这个参数就是生成椭圆所对应的矩形;
float startAngle:开始的角度,X轴正方向为0度
float sweepAngel:持续的度数;
 


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
paint.setStyle(Style.STROKE);//填充样式改为描边 
paint.setStrokeWidth(5);//设置画笔宽度
 
Path path = new Path();
RectF rect =  new RectF(50, 50, 240, 200);
path.addArc(rect, 0, 100);
 
canvas.drawPath(path, paint);//画出路径

7、线段轨迹

void quadTo (float x1, float y1, float x2, float y2)

 

二、文字

1、Paint相关设置

//普通设置
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setStyle(Paint.Style.FILL);//绘图样式,对于设文字和几何图形都有效
paint.setTextAlign(Align.CENTER);//设置文字对齐方式,取值:align.CENTER、align.LEFT或align.RIGHT
paint.setTextSize(12);//设置文字大小
 
//样式设置
paint.setFakeBoldText(true);//设置是否为粗体文字
paint.setUnderlineText(true);//设置下划线
paint.setTextSkewX((float) -0.25);//设置字体水平倾斜度,普通斜体字是-0.25
paint.setStrikeThruText(true);//设置带有删除线效果
 
//其它设置
paint.setTextScaleX(2);//只会将水平方向拉伸,高度不会

 

示例1:绘图样式的区别:


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(80);//设置文字大小
 
//绘图样式,设置为填充	
paint.setStyle(Paint.Style.FILL);	
canvas.drawText("欢迎光临Harvic的博客", 10,100, paint);
 
//绘图样式设置为描边	
paint.setStyle(Paint.Style.STROKE);
canvas.drawText("欢迎光临Harvic的博客", 10,200, paint);
 
//绘图样式设置为填充且描边	
paint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawText("欢迎光临Harvic的博客", 10,300, paint);

示例二:文字样式设置及倾斜度正负区别


Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(80);//设置文字大小
paint.setStyle(Paint.Style.FILL);//绘图样式,设置为填充	
 
//样式设置
paint.setFakeBoldText(true);//设置是否为粗体文字
paint.setUnderlineText(true);//设置下划线
paint.setStrikeThruText(true);//设置带有删除线效果
 
//设置字体水平倾斜度,普通斜体字是-0.25,可见往右斜
paint.setTextSkewX((float) -0.25);
canvas.drawText("欢迎光临Harvic的博客", 10,100, paint);
 
//水平倾斜度设置为:0.25,往左斜
paint.setTextSkewX((float) 0.25);
canvas.drawText("欢迎光临Harvic的博客", 10,200, paint);

示例三:水平拉伸设置( paint.setTextScaleX(2);)

写三行字,第一行,水平未拉伸的字体;第二行,水平拉伸两倍的字体;第三行,水平未拉伸和水平拉伸两部的字体写在一起,可以发现,仅是水平方向拉伸,高度并未改变;

Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(80);//设置文字大小
paint.setStyle(Paint.Style.FILL);//绘图样式,设置为填充	
 
//变通样式字体
canvas.drawText("欢迎光临Harvic的博客", 10,100, paint);
 
//水平方向拉伸两倍
paint.setTextScaleX(2);//只会将水平方向拉伸,高度不会变
canvas.drawText("欢迎光临Harvic的博客", 10,200, paint);
 
//写在同一位置,不同颜色,看下高度是否看的不变
paint.setTextScaleX(1);//先还原拉伸效果
canvas.drawText("欢迎光临Harvic的博客", 10,300, paint);
 
paint.setColor(Color.GREEN);
paint.setTextScaleX(2);//重新设置拉伸效果
canvas.drawText("欢迎光临Harvic的博客", 10,300, paint);

 

2、canvas绘图方式
(1)、普通水平绘制
构造函数:

void drawText (String text, float x, float y, Paint paint)
void drawText (CharSequence text, int start, int end, float x, float y, Paint paint)
void drawText (String text, int start, int end, float x, float y, Paint paint)
void drawText (char[] text, int index, int count, float x, float y, Paint paint)

说明:
第一个构造函数:最普通简单的构造函数;
第三、四个构造函数:实现截取一部分字体给图;
第二个构造函数:最强大,因为传入的可以是charSequence类型字体,所以可以实现绘制带图片的扩展文字(待续),而且还能截取一部分绘制
 

(2)、指定个个文字位置
void drawPosText (char[] text, int index, int count, float[] pos, Paint paint)
void drawPosText (String text, float[] pos, Paint paint)

说明:
第一个构造函数:实现截取一部分文字绘制;

参数说明:
char[] text:要绘制的文字数组
int index::第一个要绘制的文字的索引
int count:要绘制的文字的个数,用来算最后一个文字的位置,从第一个绘制的文字开始算起
float[] pos:每个字体的位置,同样两两一组,如{x1,y1,x2,y2,x3,y3……}
Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(80);//设置文字大小
paint.setStyle(Paint.Style.FILL);//绘图样式,设置为填充	
 
float []pos=new float[]{80,100,
						80,200,
						80,300,
						80,400};
canvas.drawPosText("画图示例", pos, paint);//两个构造函数

(3)、沿路径绘制
void drawTextOnPath (String text, Path path, float hOffset, float vOffset, Paint paint)
void drawTextOnPath (char[] text, int index, int count, Path path, float hOffset, float vOffset, Paint paint)

参数说明:

有关截取部分字体绘制相关参数(index,count),没难度,就不再讲了,下面首重讲hOffset、vOffset
float hOffset  : 与路径起始点的水平偏移距离
float vOffset  : 与路径中心的垂直偏移量

Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(45);//设置文字大小
paint.setStyle(Paint.Style.STROKE);//绘图样式,设置为填充
 
String string="风萧萧兮易水寒,壮士一去兮不复返";
 
//先创建两个相同的圆形路径,并先画出两个路径原图
Path circlePath=new Path();
circlePath.addCircle(220,200, 180, Path.Direction.CCW);//逆向绘制,还记得吗,上篇讲过的
canvas.drawPath(circlePath, paint);//绘制出路径原形
 
Path circlePath2=new Path();
circlePath2.addCircle(750,200, 180, Path.Direction.CCW);
canvas.drawPath(circlePath2, paint);//绘制出路径原形
 
paint.setColor(Color.GREEN);
//hoffset、voffset参数值全部设为0,看原始状态是怎样的
canvas.drawTextOnPath(string, circlePath, 0, 0, paint);
//第二个路径,改变hoffset、voffset参数值
canvas.drawTextOnPath(string, circlePath2, 80, 30, paint);

3、字体样式设置(Typeface)

 

在Paint中设置字体样式:

paint.setTypeface(typeface);

Typeface相关

概述:Typeface是专门用来设置字体样式的,通过paint.setTypeface()来指定。可以指定系统中的字体样式,也可以指定自定义的样式文件中获取。要构建Typeface时,可以指定所用样式的正常体、斜体、粗体等,如果指定样式中,没有相关文字的样式就会用系统默认的样式来显示,一般默认是宋体。

创建Typeface:

 Typeface    create(String familyName, int style) //直接通过指定字体名来加载系统中自带的文字样式
 Typeface    create(Typeface family, int style)     //通过其它Typeface变量来构建文字样式
 Typeface    createFromAsset(AssetManager mgr, String path) //通过从Asset中获取外部字体来显示字体样式
 Typeface    createFromFile(String path)//直接从路径创建
 Typeface    createFromFile(File path)//从外部路径来创建字体样式
 Typeface    defaultFromStyle(int style)//创建默认字体

上面的各个参数都会用到Style变量,Style的枚举值如下:
Typeface.NORMAL  //正常体
Typeface.BOLD    //粗体
Typeface.ITALIC    //斜体
Typeface.BOLD_ITALIC //粗斜体

(1)、使用系统中的字体
从上面创建Typeface的所有函数中可知,使用系统中自带的字体有下面两种方式来构造Typeface:

 Typeface    defaultFromStyle(int style)//创建默认字体
 Typeface    create(String familyName, int style) //直接通过指定字体名来加载系统中自带的文字样式

其实,第一个仅仅是使用系统默认的样式来绘制字体,基本没有可指定性,就不再讲了,使用起来难度也不大,下面只以第二个构造函数为例,指定宋体绘制:
 


//使用系统自带字体绘制		
Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(60);//设置文字大小
paint.setStyle(Paint.Style.STROKE);//绘图样式,设置为填充
 
String familyName = "宋体";
Typeface font = Typeface.create(familyName,Typeface.NORMAL);
paint.setTypeface(font);
canvas.drawText("欢迎光临Harvic的博客",10,100, paint);

2、自字义字体
自定义字体的话,我们就需要从外部字体文件加载我们所需要的字形的,从外部文件加载字形所使用的Typeface构造函数如下面三个:
 Typeface    createFromAsset(AssetManager mgr, String path) //通过从Asset中获取外部字体来显示字体样式
 Typeface    createFromFile(String path)//直接从路径创建
 Typeface    createFromFile(File path)//从外部路径来创建字体样式

后面两个从路径加载难度不大,而我们一般也不会用到,这里我们说说从Asset文件中加载;

首先在Asset下建一个文件夹,命名为Fonts,然后将字体文件jian_luobo.ttf 放入其中
 

//自定义字体,,,迷你简罗卜
Paint paint=new Paint();
paint.setColor(Color.RED);  //设置画笔颜色    
 
paint.setStrokeWidth (5);//设置画笔宽度
paint.setAntiAlias(true); //指定是否使用抗锯齿功能,如果使用,会使绘图速度变慢
paint.setTextSize(60);//设置文字大小
paint.setStyle(Paint.Style.FILL);//绘图样式,设置为填充
 
AssetManager mgr=m_context.getAssets();//得到AssetManager
Typeface typeface=Typeface.createFromAsset(mgr, "fonts/jian_luobo.ttf");//根据路径得到Typeface
paint.setTypeface(typeface);
Log.v("msg",typeface.toString());
canvas.drawText("欢迎光临Harvic的博客",10,100, paint);//两个构造函数

 

 

一、构造Region

 public Region()  //创建一个空的区域  
 public Region(Region region) //拷贝一个region的范围  
 public Region(Rect r)  //创建一个矩形的区域  
 public Region(int left, int top, int right, int bottom) //创建一个矩形的区域  

上面的四个构造函数,第一个还要配合其它函数使用,暂时不提。
第二个构造函数是通过其它的Region来复制一个同样的Region变量
第三个,第四个才是正规常的,根据一个矩形或矩形的左上角和右下角点构造出一个矩形区域
 

2、间接构造
 public void setEmpty()  //置空
 public boolean set(Region region)   
 public boolean set(Rect r)   
 public boolean set(int left, int top, int right, int bottom)   
 public boolean setPath(Path path, Region clip)//后面单独讲

这是Region所具有的一系列Set方法,我这里全部列了出来,下面一一对其讲解:
注意:无论调用Set系列函数的Region是不是有区域值,当调用Set系列函数后,原来的区域值就会被替换成Set函数里的区域。
SetEmpty():从某种意义上讲置空也是一个构造函数,即将原来的一个区域变量变成了一个空变量,要再利用其它的Set方法重新构造区域。
set(Region region):利用新的区域值来替换原来的区域
set(Rect r):利用矩形所代表的区域替换原来的区域
set(int left, int top, int right, int bottom):同样,根据矩形的两个点构造出矩形区域来替换原来的区域值
setPath(Path path, Region clip):根据路径的区域与某区域的交集,构造出新区域,这个后面具体讲解
个小例子,来说明一个Set系列函数的替换概念:

public class MyRegionView extends View {
 
	public MyRegionView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		//初始化画笔
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		paint.setStyle(Style.FILL);
		paint.setStrokeWidth(2);
		
		Region rgn = new Region(10,10,100,100);
        //使用Set函数后,替换为新区域
		rgn.set(100, 100, 200, 200);
		drawRegion(canvas, rgn, paint);
		
	}
	
	//这个函数不懂没关系,下面会细讲
	private void drawRegion(Canvas canvas,Region rgn,Paint paint)
	{
		RegionIterator iter = new RegionIterator(rgn);
		Rect r = new Rect();
		
		while (iter.next(r)) {
		  canvas.drawRect(r, paint);
		} 
	}
 
}

 

3、使用SetPath()构造不规则区域
boolean setPath (Path path, Region clip)

参数说明:
Path path:用来构造的区域的路径
Region clip:与前面的path所构成的路径取交集,并将两交集设置为最终的区域

由于路径有很多种构造方法,而且可以轻意构造出非矩形的路径,这就摆脱了前面的构造函数只能构造矩形区域的限制。但这里有个问题是要指定另一个区域来取共同的交集,当然如果想显示路径构造的区域,Region clip参数可以传一个比Path范围大的多的区域,取完交集之后,当然是Path参数所对应的区域喽。机智的孩子。

下面,先构造一个椭圆路径,然后在SetPath时,传进去一个比Path小的矩形区域,让它们两个取交集
 

public class MyRegionView extends View {
 
	public MyRegionView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		//初始化Paint
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		paint.setStyle(Style.FILL);
		paint.setStrokeWidth(2);
		//构造一个椭圆路径
		Path ovalPath = new Path();
		RectF rect =  new RectF(50, 50, 200, 500);  
		ovalPath.addOval(rect, Direction.CCW);
		//SetPath时,传入一个比椭圆区域小的矩形区域,让其取交集
		Region rgn = new Region();
		rgn.setPath(ovalPath,new  Region(50, 50, 200, 200));
		//画出路径
		drawRegion(canvas, rgn, paint);
	}
	
	//这个函数不懂没关系,下面会细讲
	private void drawRegion(Canvas canvas,Region rgn,Paint paint)
	{
		RegionIterator iter = new RegionIterator(rgn);
		Rect r = new Rect();
		
		while (iter.next(r)) {
		  canvas.drawRect(r, paint);
		} 
	}
}

二、矩形集枚举区域——RegionIterator类
对于特定的区域,我们都可以使用多个矩形来表示其大致形状。事实上,如果矩形足够小,一定数量的矩形就能够精确表示区域的形状,也就是说,一定数量的矩形所合成的形状,也可以代表区域的形状。RegionIterator类,实现了获取组成区域的矩形集的功能,其实RegionIterator类非常简单,总共就两个函数,一个构造函数和一个获取下一个矩形的函数;
RegionIterator(Region region) //根据区域构建对应的矩形集
boolean    next(Rect r) //获取下一个矩形,结果保存在参数Rect r 中

由于在Canvas中没有直接绘制Region的函数,我们想要绘制一个区域,就只能通过利用RegionIterator构造矩形集来逼近的显示区域。用法如下:
 

private void drawRegion(Canvas canvas,Region rgn,Paint paint)
{
	RegionIterator iter = new RegionIterator(rgn);
	Rect r = new Rect();
	
	while (iter.next(r)) {
	  canvas.drawRect(r, paint);
	} 
}

面我们也都看到了它的用法,首先,根据区域构建一个矩形集,然后利用next(Rect r)来逐个获取所有矩形,绘制出来,最终得到的就是整个区域,如果我们将上面的画笔Style从FILL改为STROKE,重新绘制椭圆路径,会看得更清楚。

三、区域的合并、交叉等操作
无论是区域还是矩形,都会涉及到与另一个区域的一些操作,比如取交集、取并集等,涉及到的函数有:

public final boolean union(Rect r)   
public boolean op(Rect r, Op op) {  
public boolean op(int left, int top, int right, int bottom, Op op)   
public boolean op(Region region, Op op)   
public boolean op(Rect rect, Region region, Op op)   

除了Union(Rect r)是指定合并操作以外,其它四个op()构造函数,都是指定与另一个区域的操作。其中最重要的指定Op的参数,Op的参数有下面四个:
 

假设用region1  去组合region2   
public enum Op {  
        DIFFERENCE(0), //最终区域为region1 与 region2不同的区域  
        INTERSECT(1), // 最终区域为region1 与 region2相交的区域  
        UNION(2),      //最终区域为region1 与 region2组合一起的区域  
        XOR(3),        //最终区域为region1 与 region2相交之外的区域  
        REVERSE_DIFFERENCE(4), //最终区域为region2 与 region1不同的区域  
        REPLACE(5); //最终区域为为region2的区域  
 } 

 

先构造两个相交叉的矩形,并画出它们的轮廓

//构造两个矩形
Rect rect1 = new Rect(100,100,400,200);
Rect rect2 = new Rect(200,0,300,300);
 
//构造一个画笔,画出矩形轮廓
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
 
canvas.drawRect(rect1, paint);
canvas.drawRect(rect2, paint);
然后利用上面的两年rect,(rect1和rect2)来构造区域,并在rect1的基础上取与rect2的交集
//构造两个Region
Region region = new Region(rect1);
Region region2= new Region(rect2);
 
//取两个区域的交集		
region.op(region2, Op.INTERSECT);
最后构造一个填充画笔,将所选区域用绿色填充起来
Paint paint_fill = new Paint();
paint_fill.setColor(Color.GREEN);
paint_fill.setStyle(Style.FILL);
drawRegion(canvas, region, paint_fill)

 

/**
 * created by harvic
 * 2014/9/4
 */
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Paint.Style;
import android.graphics.Region.Op;
import android.graphics.RegionIterator;
import android.view.View;
 
public class MyRegionView extends View {
 
	public MyRegionView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		//构造两个矩形
		Rect rect1 = new Rect(100,100,400,200);
		Rect rect2 = new Rect(200,0,300,300);
		
		//构造一个画笔,画出矩形轮廓
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		paint.setStyle(Style.STROKE);
		paint.setStrokeWidth(2);
		
		canvas.drawRect(rect1, paint);
		canvas.drawRect(rect2, paint);
		
		
		
		//构造两个Region
		Region region = new Region(rect1);
		Region region2= new Region(rect2);
 
		//取两个区域的交集		
		region.op(region2, Op.INTERSECT);
		
		//再构造一个画笔,填充Region操作结果
		Paint paint_fill = new Paint();
		paint_fill.setColor(Color.GREEN);
		paint_fill.setStyle(Style.FILL);
		drawRegion(canvas, region, paint_fill);
 
	}
	
 
private void drawRegion(Canvas canvas,Region rgn,Paint paint)
{
	RegionIterator iter = new RegionIterator(rgn);
	Rect r = new Rect();
	
	while (iter.next(r)) {
	  canvas.drawRect(r, paint);
	} 
}
}

 

四、其它一些方法
Region类除了上面的一些重要的方法以外,还有一些比较容易理解的方法,我就不再一一列举用法了,下面一并列出给大家
/**几个判断方法*/  
public native boolean isEmpty();//判断该区域是否为空  
public native boolean isRect(); //是否是一个矩阵  
public native boolean isComplex();//是否是多个矩阵组合  
  
  
/**一系列的getBound方法,返回一个Region的边界*/  
public Rect getBounds()   
public boolean getBounds(Rect r)   
public Path getBoundaryPath()   
public boolean getBoundaryPath(Path path)   
  
  
/**一系列的判断是否包含某点 和是否相交*/  
public native boolean contains(int x, int y);//是否包含某点  
public boolean quickContains(Rect r)   //是否包含某矩形
public native boolean quickContains(int left, int top, int right,  
                                        int bottom) //是否没有包含某矩阵形 
 public boolean quickReject(Rect r) //是否没和该矩形相交  
 public native boolean quickReject(int left, int top, int right, int bottom); //是否没和该矩形相交  
 public native boolean quickReject(Region rgn);  //是否没和该矩形相交  
  
/**几个平移变换的方法*/  
public void translate(int dx, int dy)   
public native void translate(int dx, int dy, Region dst);  
public void scale(float scale) //hide  
public native void scale(float scale, Region dst);//hide

 

 

 

一、canvas变换与操作

(1)平移(translate)

void translate(float dx, float dy)

参数说明:
float dx:水平方向平移的距离,正数指向正方向(向右)平移的量,负数为向负方向(向左)平移的量
flaot dy:垂直方向平移的距离,正数指向正方向(向下)平移的量,负数为向负方向(向上)平移的量

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
	//translate  平移,即改变坐标系原点位置
	
	Paint paint = new Paint();
	paint.setColor(Color.GREEN);
	paint.setStyle(Style.FILL);
	
//	canvas.translate(100, 100);//从左上角x=0,y=0平移到 x=100,y=100
	Rect rect1 = new Rect(0,0,400,220);
	canvas.drawRect(rect1, paint);
}

 

(2)屏幕显示与Canvas的关系

每次Canvas画图时(即调用Draw系列函数),都会产生一个透明图层,然后在这个图层上画图,画完之后覆盖在屏幕上显示。

 

(3)旋转(Rotate)

画布的旋转是默认是围绕坐标原点来旋转的,这里容易产生错觉,看起来觉得是图片旋转了,其实我们旋转的是画布,以后在此画布上画的东西显示出来的时候全部看起来都是旋转的。其实Roate函数有两个构造函数:

void rotate(float degrees)
void rotate (float degrees, float px, float py)

第一个构造函数直接输入旋转的度数,正数是顺时针旋转,负数指逆时针旋转,它的旋转中心点是原点(0,0)
第二个构造函数除了度数以外,还可以指定旋转的中心点坐标(px,py)

下面以第一个构造函数为例,旋转一个矩形,先画出未旋转前的图形,然后再画出旋转后的图形;
 

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
 
	Paint paint_green = generatePaint(Color.GREEN, Style.FILL, 5);
	Paint paint_red   = generatePaint(Color.RED, Style.STROKE, 5);
	
	Rect rect1 = new Rect(300,10,500,100);
	canvas.drawRect(rect1, paint_red); //画出原轮廓
	
	canvas.rotate(30);//顺时针旋转画布
	canvas.drawRect(rect1, paint_green);//画出旋转后的矩形
} 

 

(4)缩放(scale )

public void scale (float sx, float sy) 
public final void scale (float sx, float sy, float px, float py)

其实我也没弄懂第二个构造函数是怎么使用的,我就先讲讲第一个构造函数的参数吧
float sx:水平方向伸缩的比例,假设原坐标轴的比例为n,不变时为1,在变更的X轴密度为n*sx;所以,sx为小数为缩小,sx为整数为放大
float sy:垂直方向伸缩的比例,同样,小数为缩小,整数为放大

注意:这里有X、Y轴的密度的改变,显示到图形上就会正好相同,比如X轴缩小,那么显示的图形也会缩小。一样的。
 

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
//	//scale 缩放坐标系密度
	Paint paint_green = generatePaint(Color.GREEN, Style.STROKE, 5);
	Paint paint_red   = generatePaint(Color.RED, Style.STROKE, 5);
	
	Rect rect1 = new Rect(10,10,200,100);
	canvas.drawRect(rect1, paint_green);
	
	canvas.scale(0.5f, 1);
	canvas.drawRect(rect1, paint_red);
} 

 

(5)扭曲(skew)

void skew (float sx, float sy)

参数说明:
float sx:将画布在x方向上倾斜相应的角度,sx倾斜角度的tan值,
float sy:将画布在y轴方向上倾斜相应的角度,sy为倾斜角度的tan值,

注意,这里全是倾斜角度的tan值哦,比如我们打算在X轴方向上倾斜60度,tan60=根号3,小数对应1.732
 

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
	//skew 扭曲
	Paint paint_green = generatePaint(Color.GREEN, Style.STROKE, 5);
	Paint paint_red   = generatePaint(Color.RED, Style.STROKE, 5);
	
	Rect rect1 = new Rect(10,10,200,100);
 
	canvas.drawRect(rect1, paint_green);
	canvas.skew(1.732f,0);//X轴倾斜60度,Y轴不变
	canvas.drawRect(rect1, paint_red);
} 

 

(6)裁剪画布(clip系列函数)

裁剪画布是利用Clip系列函数,通过与Rect、Path、Region取交、并、差等集合运算来获得最新的画布形状。除了调用Save、Restore函数以外,这个操作是不可逆的,一但Canvas画布被裁剪,就不能再被恢复!
Clip系列函数如下:
boolean    clipPath(Path path)
boolean    clipPath(Path path, Region.Op op)
boolean    clipRect(Rect rect, Region.Op op)
boolean    clipRect(RectF rect, Region.Op op)
boolean    clipRect(int left, int top, int right, int bottom)
boolean    clipRect(float left, float top, float right, float bottom)
boolean    clipRect(RectF rect)
boolean    clipRect(float left, float top, float right, float bottom, Region.Op op)
boolean    clipRect(Rect rect)
boolean    clipRegion(Region region)
boolean    clipRegion(Region region, Region.Op op)
 

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
	canvas.drawColor(Color.RED);
	canvas.clipRect(new Rect(100, 100, 200, 200));
	canvas.drawColor(Color.GREEN);
} 

(7)画布的保存与恢复(save()、restore())

int save ()
void    restore()
Save():每次调用Save()函数,都会把当前的画布的状态进行保存,然后放入特定的栈中;
restore():每当调用Restore()函数,就会把栈中最顶层的画布状态取出来,并按照这个状态恢复当前的画布,并在这个画布上做画。
 

protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
	canvas.drawColor(Color.RED);
	
	//保存当前画布大小即整屏
	canvas.save(); 
	
	canvas.clipRect(new Rect(100, 100, 800, 800));
	canvas.drawColor(Color.GREEN);
	
	//恢复整屏画布
	canvas.restore();
	
	canvas.drawColor(Color.BLUE);
} 
protected void onDraw(Canvas canvas) {
	// TODO Auto-generated method stub
	super.onDraw(canvas);
	
	canvas.drawColor(Color.RED);
	//保存的画布大小为全屏幕大小
	canvas.save();
	
	canvas.clipRect(new Rect(100, 100, 800, 800));
	canvas.drawColor(Color.GREEN);
	//保存画布大小为Rect(100, 100, 800, 800)
	canvas.save();
	
	canvas.clipRect(new Rect(200, 200, 700, 700));
	canvas.drawColor(Color.BLUE);
	//保存画布大小为Rect(200, 200, 700, 700)
	canvas.save();
	
	canvas.clipRect(new Rect(300, 300, 600, 600));
	canvas.drawColor(Color.BLACK);
	//保存画布大小为Rect(300, 300, 600, 600)
	canvas.save();
	
	canvas.clipRect(new Rect(400, 400, 500, 500));
	canvas.drawColor(Color.WHITE);
} 

在这段代码中,总共调用了四次Save操作。上面提到过,每调用一次Save()操作就会将当前的画布状态保存到栈中,所以这四次Save()所保存的状态的栈的状态如下:

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值