ImageView通过矩阵旋转改变位置

时间:2016-05-07 17:52:36

标签: android android-imageview image-rotation

在android中我有一个嵌套的imageView我必须旋转外部图像而不改变初始位置。但是如果我使用矩阵来旋转图像它会改变位置。我怎么能这样做?

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.partha.rotate_check.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:src="@mipmap/meter"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="49dp" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView2"
    android:src="@mipmap/cursor"
    android:layout_below="@+id/imageView"
    android:layout_alignTop="@+id/imageView"
    android:layout_alignBottom="@+id/imageView"
    android:layout_alignLeft="@+id/imageView"
    android:layout_alignRight="@+id/imageView"
    android:scaleType="fitXY"/>
</RelativeLayout>

代码

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView meter=(ImageView)findViewById(R.id.imageView);
    ImageView cursor=(ImageView)findViewById(R.id.imageView2);
    meter.getLayoutParams().height=300;
    meter.getLayoutParams().width=300;
    Matrix matrix = new Matrix();
    cursor.setScaleType(ImageView.ScaleType.MATRIX);
    matrix.postRotate((float) 30, cursor.getWidth()/2, cursor.getHeight()/2); // same result if i use cursor.getPivotx() method
    cursor.setImageMatrix(matrix);



}

}

1 个答案:

答案 0 :(得分:0)

当时不知道宽度和高度。你需要等到他们被测量,你可以尝试这样:

    final ImageView cursor=(ImageView)findViewById(R.id.imageView2);
    cursor.post(new Runnable() {
        @Override
        public void run() {
            Matrix matrix = new Matrix();
            cursor.setScaleType(ImageView.ScaleType.MATRIX);
            matrix.postRotate((float) 30, cursor.getWidth()/2, cursor.getHeight()/2); // same result if i use cursor.getPivotx() method
            cursor.setImageMatrix(matrix);

        }
    });

或使用PreDrawListener。