温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-06-28 17:09:20 来源:亿速云 阅读:192 作者:Leah 栏目:移动开发

Android 中View.onDraw(Canvas canvas)方法如何使用,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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); 
    } 
  } 
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI