每次点击图片一次,图片旋转90°
第一步:自定义ImageView
1 /** 2 * @author Sigal 3 * on 2018/12/17 4 * note: 每次点击旋转90度的ImageView 5 */ 6 @SuppressLint("AppCompatCustomView") 7 public class RotateImageView extends ImageView { 8 int mdegree =0; 9 10 public RotateImageView(Context context, AttributeSet attrs) { 11 super(context, attrs); 12 } 13 14 public RotateImageView(Context context) { 15 super(context); 16 } 17 18 @Override 19 protected void onDraw(Canvas canvas) { 20 int top = getTop(); 21 int left = getLeft(); 22 int right = getRight(); 23 int bottom = getBottom(); 24 float centralX = (right - left) / 2.0f; 25 float centralY = (bottom - top) / 2.0f; 26 //保存旋转前画布状态 27 canvas.save(); 28 canvas.rotate(mdegree, centralX, centralY); 29 super.onDraw(canvas); 30 //取去出旋转前保存的状态 31 canvas.restore(); 32 } 33 public void setDegree(int degree) { 34 mdegree = degree; 35 invalidate(); 36 } 37 }
第二步:调用RotateImageView
1 RotateImageView imageView = findViewById(R.id.img); 2 imageView.setOnClickListener(new View.OnClickListener() { 3 @Override 4 public void onClick(View v) { 5 count++; 6 imageView.setDegree(90*count); 7 } 8 });
第三步:布局文件
<com.sun.test01.RotateImageView android:id="@+id/img" android:layout_width="200dp" android:layout_height="300dp" android:scaleType="centerInside" android:src="@drawable/img_02" />