您的位置:首页 > 产品设计 > UI/UE

在GUI中旋转图片

2015-03-02 18:23 78 查看
2种写法

用API: GUIUtility.RotateAroundPivot

public static void RotateAroundPivot(float angle, Vector2 pivotPoint);


围绕pivotPoint(屏幕坐标,要特别注意ui有缩放时需要使用缩放之前的屏幕坐标)旋转角度angle。内部机制是修改GUI.matrix。

Texture touchTexture;
Vector2 rotatePivot = new Vector2(100,200);
//draw之前先旋转角度
GUIUtility.RotateAroundPivot (rotAngle, rotatePivot);
GUI.DrawTexture(drawRect , touchTexture);
//draw之后恢复此前旋转的角度
GUIUtility.RotateAroundPivot (-rotAngle, rotatePivot);


RotateAroundPivot操作会对之后所有的draw实施旋转,如果只让本次draw旋转生效,需要draw后再转回去。

因为内部机制是修改了GUI.matrix,通过还原GUI.matrix也可以;

Matrix4x4 _matrix = GUI.matrix;
GUIUtility.RotateAroundPivot (rotAngle, rotatePivot);
GUI.DrawTexture(drawRect , touchTexture);
GUI.matrix = _matrix;


一个实例:

用第三方插件easy joystick做摇杆,需求是随着力度和角度变化摇杆touch的touchTexture需要变化,而不是一个固定的图片。easy joystick本身只支持单张图片,因此需要扩展easy joystick。

先解决旋转角度问题

在EasyJoystick.OnGUI()里touchTexture绘制的地方修改如下:



GUI.DrawTexture( new Rect(anchorPosition.x +  joystickCenter.x+(joystickTouch.x -touchSize) ,anchorPosition.y + joystickCenter.y-(joystickTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true);


改为

float rotAngle = 45;
Rect drawRect = new Rect(anchorPosition.x +  joystickCenter.x+(joystickTouch.x -touchSize) ,anchorPosition.y + joystickCenter.y-(joystickTouch.y+touchSize),touchSize*2,touchSize*2);
Matrix4x4 _matrix = GUI.matrix;
Rect realRect = VirtualScreen.GetRealRect(drawRect);
GUIUtility.RotateAroundPivot (rotAngle, new Vector2(realRect.x+realRect.width/2.0f, realRect.y+realRect.height/2.0f));
GUI.DrawTexture (drawRect, touchTexture, ScaleMode.ScaleToFit);
GUI.matrix = _matrix;


运行起来可以看到touchTexture旋转了45度,默认的素材是圆看不出旋转,在joystick textures里把素材换成其他形状。

在easyjoystick的OnGUI()里做了gui的缩放,真实的屏幕尺寸映射到了虚拟屏幕尺寸:

VirtualScreen.SetGuiScaleMatrix();


easyjoystick里的绘制draw基于虚拟屏幕尺寸。

VirtualScreen.GetRealRect()的作用是将easy joystic里虚拟屏幕坐标转换为真实的屏幕坐标。

旋转操作RotateAroundPivot是基于真实的屏幕坐标的,这里如果直接写成

GUIUtility.RotateAroundPivot (rotAngle, new Vector2(drawRect.x+drawRect.width/2.0f, drawRect.y+drawRect.height/2.0f));

会发现touchTexture虽然是旋转了45度,但是位置不是touch的位置。

自此旋转问题解决,接下来是计算角度。

2. 计算角度:

float rotAngle = Mathf.Atan2( joystickAxis.x,joystickAxis.y ) * Mathf.Rad2Deg;

3. 计算距离:根据摇杆移动的距离替换图片

float maxv = Mathf.Max(Mathf.Abs(JoystickTouch.x), Mathf.Abs(JoystickTouch.y));

string yaoganid = “yoagan”+maxv;

touchTexture = Resources.Load(“UIs/textures/yaogan/yaogan” + yaoganid) as Texture;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: