是否有一种简单的方法可以在画布上绘制矩形并将其显示在像TextView这样的活动中?
我试图像这样绘制我的矩形:
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.MAGENTA);
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Rect locationrect = new Rect(10, 10, 200, 100);
c.drawRect(locationrect, paint);
View locationpic = (View)findViewById(R.id.locationview);
locationpic.draw(c);
在我的xml中:
<View
android:id="@+id/locationview"
android:layout_width="520dp"
android:layout_height="489dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="220dp" />
这显然不起作用(它没有崩溃,但没有显示矩形)..任何帮助将不胜感激! 谢谢!
答案 0 :(得分:1)
创建一个Java文件并写下:
package com.samplecanvas;
import java.util.ArrayList;
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.os.Bundle; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout;
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View;
public class SampleCanvasActivity extends View {
vPaint paint = new Paint();
public SampleCanvasActivity(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(130, 130, 180, 180, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(133, 160, 177, 177, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(133, 133, 177, 160, paint );
}
}
在ur xml中使用此文件
喜欢这个。
<com.samplecanvas.SampleCanvasActivity
android:id="@+id/widthView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="150dp"
/>