扩展ImageView使可旋转

本文介绍了一种通过继承Android的ImageView来实现可旋转图片显示的方法。该组件新增了angle属性,允许开发者轻松调整图片的角度,并详细展示了如何在代码中实现角度测量与绘制过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承ImageView,增加angle属性,重写OnMeasure和OnDraw方法

package com.upon.common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.upon.xxxx.R;

public class UponRotateImageView extends ImageView {

private int mAngle;

public UponRotateImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
loadAttributes(context, attrs);
}

public UponRotateImageView(Context context, AttributeSet attrs) {
super(context, attrs);
loadAttributes(context, attrs);
}

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

private void loadAttributes(Context context, AttributeSet attrs) {
TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.RotateImageView);
mAngle = arr.getInteger(R.styleable.RotateImageView_angle, 0);
arr.recycle();
}

public int getAngle() {
return mAngle;
}

public void setAngle(int angle) {
mAngle = angle;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int w = getDrawable().getIntrinsicWidth();
int h = getDrawable().getIntrinsicHeight();
double a = Math.toRadians(mAngle);

int width = (int) (Math.abs(w * Math.cos(a)) + Math.abs(h * Math.sin(a)));
int height = (int) (Math.abs(w * Math.sin(a)) + Math.abs(h * Math.cos(a)));

setMeasuredDimension(width, height);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(mAngle % 360, getWidth() / 2, getHeight() / 2);
getDrawable().draw(canvas);
canvas.restore();
}
}

attrs.xm文件中增加angle属性


<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RotateImageView">
<attr name="angle" format="integer" />
</declare-styleable>

</resources>


使用UponRotateImageView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:upon="http://schemas.android.com/apk/res/com.upon.xxxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<com.upon.common.view.UponRotateImageView
android:id="@+id/bkg_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/conquer_nation_bkg"
upon:angle="45" />

</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值