【问题标题】:Rotating rectangle on canvas android在画布android上旋转矩形
【发布时间】:2015-07-31 00:19:47
【问题描述】:

我创建了一个将另一个活动设置为视图的活动,在这个活动中我创建了画布(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);

      }
 }

谢谢大家:)

【问题讨论】:

    标签: android canvas rectangles


    【解决方案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);
    

    【讨论】:

    • 你编辑的部分,View xml文件,应该放在哪里?
    • 嗯,大多数应用都会使用layout xml。
    • 好吧,使用视图动画的整个想法是您不必弄乱画布。
    【解决方案2】:

    绘制前需要旋转:

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

    【讨论】:

    • 然后我不能旋转吗?我的意思是,我想创建一个矩形,查看它,然后旋转它..
    • Emm.. 我希望它快速旋转,如果你触摸它会发生一些事情,如果我像旋转一样动画它,命令“rec1.contains(x,y)”仍然有效?
    • 你考虑过使用animations吗?
    • 你知道如何制作旋转动画吗?以及如何永远循环它,我希望它永远旋转
    猜你喜欢
    • 2012-11-27
    • 2016-08-05
    • 2019-03-07
    • 2021-10-07
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多