代码之家  ›  专栏  ›  技术社区  ›  Sam

Android画布填充背景颜色(画布应用程序)

  •  9
  • Sam  · 技术社区  · 12 年前

    通过以下代码,我有一些问题。

    public class MainActivity extends Activity {
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView( new View(this) {
             Paint mPaint = new Paint();
    
             @Override
             protected void onDraw(Canvas canvas) {
                // TODO Auto-generated method stub
                super.onDraw(canvas);
    
    
                int width = this.getWidth();
                int height = this.getHeight();
                int radius = width > height ? height/2 : width/2;
                int center_x = width/2;
                int center_y = height/2;
    
                // prepare a paint
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setStrokeWidth(5);
                mPaint.setAntiAlias(true);
    
                // draw a rectangle
                mPaint.setColor(Color.BLUE);
                    mPaint.setStyle(Paint.Style.FILL); //fill the background with blue color
                canvas.drawRect(center_x - radius, center_y - radius, center_x + radius, center_y + radius, mPaint);
                // draw some text and rotation
                mPaint.setTextSize(50);
                mPaint.setTextAlign(Paint.Align.CENTER);
                mPaint.setColor(Color.BLACK);
                canvas.drawText( "Hello World" , center_x , center_y, mPaint);
             }
          });
        }
    }
    

    enter image description here

    Q1:如何在相框中填充蓝色?(文字仍然出现)

    Q2:这个应用程序中有多少视图和曲面?我如何在应用程序中计算这些?

    问题3:这个应用程序有多少个窗口?

    Q4:在代码中,我没有看到任何位图对象。 然而,我认为位图是我真正可以在上面画东西的对象 理解不正确? 一种可能性是Canvas构造函数在位图新建时对其进行初始化。

    问题5:我知道这些图形最终会浮出水面,然后传递给 最终成分的表面活性剂。它在我的代码中的位置?

    谢谢你的回复。

    3 回复  |  直到 12 年前
        1
  •  8
  •   jboi    12 年前

    五个问题。让我们看看我能在哪里帮忙。

    Q1:告诉 Paint 要填充矩形: paint.setStyle(Paint.Style.FILL);

    Q2:我只看到您以编程方式创建的一个视图。你为什么要数视图?

    Q3:再次:一

    Q4:通过用 Canvas .实际绘制的方法是 帆布

    问题5:您显示的代码是“活动”的一部分。“活动”由安卓系统调用。这是您进入应用程序的入口。

        2
  •  7
  •   Puffy    9 年前

    谢谢你的回答。我完成了为标记答案编写代码的工作,它很有效。

        Bitmap bg = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bg);
        // paint background with the trick
        Paint rect_paint = new Paint();
        rect_paint.setStyle(Paint.Style.FILL);
        rect_paint.setColor(Color.rgb(0, 0, 0));
        rect_paint.setAlpha(0x80); // optional
        canvas.drawRect(0, 0, width, height, rect_paint); // that's painting the whole canvas in the chosen color.
    
        3
  •  0
  •   Peter Zhao    12 年前

    Q2:当你想计算应用程序中的视图数量时,层次结构查看器非常有用。 Optimizing Your UI