画布上的旋转矩形android

时间:2015-07-31 00:19:48

标签: android canvas rectangles

我创建了一个活动,将另一个活动设置为视图,在此活动中我创建了Canvas(onDraw)并在矩形内部,现在我想要旋转它,我尝试了canvas.rotate()但似乎没有任何反应。这是我的代码:

public class DrawView extends View {
Paint paint = new Paint();
private Rect rec1;

public DrawView(Context context) {
    super(context);
}

protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    DisplayMetrics metrics = new DisplayMetrics();
    ((Activity)    getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int y = metrics.heightPixels;
    int x = metrics.widthPixels;
    rec1 = new Rect(x / 2 - 25, 0, x / 2 + 25, y);
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(3);
    canvas.drawRect(rec1, paint);
    for (int j = 1; j <= 200; j++) {
        canvas.rotate(5);
    }
}

任何人都知道问题是什么?我还检查了问题是否在for中,因此我将其删除并添加了一行canvas.rotate(45),但没有。

如果需要,这里是MainActivity

import android.app.Activity;
    import android.graphics.Color;
    import android.os.Bundle;

public class MainActivity extends Activity {
DrawView drawView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(drawView);

      }
 }

谢谢大家:)

2 个答案:

答案 0 :(得分:1)

动画/ rotate.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:repeatMode="restart"
    android:repeatCount="infinite"
    android:interpolator="@android:anim/linear_interpolator"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1500" />
<View
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="#f90"
    android:id="@+id/rect"/>
View rect = findViewById(R.id.rect);
Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate);
rect.startAnimation(rotate);

答案 1 :(得分:0)

在绘制之前需要旋转:

canvas.rotate(45);
canvas.drawRect(rec1, paint);