Android Canvas Android 中View.onDraw(Canvas canvas)如何使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android Canvas Android 中View.onDraw(Canvas canvas)如何使用

zhangqijie001   2021-03-29 我要评论
想了解Android 中View.onDraw(Canvas canvas)怎样使用的相关内容吗,zhangqijie001在本文为您仔细讲解Android Canvas 的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,Canvas的使用,Android,Canvas中View.onDraw使用方法,下面大家一起来学习吧。

Android 中View.onDraw(Canvas canvas)的使用方法

View通过View.onDraw(Canvas canvas)来Draw.

我们可以定义自己的继承于View的TestView,然后重载View.onDraw(Canvas canvas).

对于自定义的TestView如何与Activity关联?有以下两种方式:

  1. 直接在setContentView(View view)里面加进去自定义的View:setContentView(new TestView(this)).
  2. 另外,可以在layout文件里面可以使用自定义的View(如何自定义的View为内部类,就会失效),

如:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  xmlns:android="http://schemas.android.com/apk/res/android"> 
  <com.android.test.TestView 
    android:id="@+id/testview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/> 
</FrameLayout> 

 以下为使用onDraw(Canvas canvas)画矩形区域,及在其上画文本的实例(通过使用内部类使程序显得更加简洁,紧凑):

package com.android.test; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Rect; 
import android.graphics.Typeface; 
import android.os.Bundle; 
import android.view.View; 
public class TestActivity extends Activity { 
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(new TestView(this)); 
  } 
  public class TestView extends View { 
    private Paint mPaint = new Paint(); 
    public TestView(Context context) { 
      super(context); 
    } 
     
    @Override 
    protected void onDraw(Canvas canvas) { 
      // TODO Auto-generated method stub 
      super.onDraw(canvas); 
       
      String text = "Android - 机器人";      
      mPaint.setColor(Color.WHITE); 
       
      Paint paint = new Paint(); 
      paint.setColor(Color.RED); 
       
      String familyName = "宋体"; 
      Typeface font = Typeface.create(familyName,Typeface.BOLD); 
      paint.setTypeface(font); 
       
      paint.setTextSize(22); 
       
      canvas.drawRect(new Rect(0, 0, 320, 240), mPaint); 
      canvas.drawText(text, 0, 100, paint); 
    } 
  } 
} 

 运行效果如下图:

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们