Tips贴图标边缘显示
图左:当左边宽度不足于容纳Tips时,Tips放在右侧显示,顶和图标对齐
图右:当左边宽度足够容纳Tips时,Tips放在左侧显示,顶和图标对齐
贴边示例
获取Mesh的四个顶点坐标
我的实现思路是获取图标的四个顶点坐标,根据顶点在屏幕的坐标,计算Tip应该放在左边还是右边
获取四个顶点算法如下:
//获取UI元素的屏幕坐标,四个坐标点的顺序为:左下 左上 右上 右下
public static Vector3[] GetUIScreenPosition(Canvas canvas,RectTransform trans)
{
Vector3[] posArray = new Vector3[4];
if (trans == null)
{
Log.Warning("canvas={0}或trans={1} ,为空",canvas,trans);
posArray[0] = Vector3.zero;
return posArray;
}
//NOTE 如果界面是以Camera方式渲染
if (canvas && canvas.worldCamera)
{
CanvasScaler scaler = canvas.GetComponent<CanvasScaler>();
//Log.Info("uiName={0},渲染模式为Camera", canvas.name);
//NOTE 这种方式获取的坐标在图标中心点,计算出四个点的坐标
var centerPos = canvas.worldCamera.WorldToScreenPoint(trans.position);
//这里不直接使用canvas.localScale.x,而是通过屏幕大小/设定分辨率 = 缩放系数
var scaleFact = Screen.width/scaler.referenceResolution.x;
var iconWidth = trans.sizeDelta.x*scaleFact;
var iconHeight = trans.sizeDelta.y*scaleFact;
//找到的点在中心点
posArray[0] = new Vector3(centerPos.x - iconWidth*0.5f, centerPos.y - iconHeight*0.5f, 0);
posArray[1] = new Vector3(centerPos.x - iconWidth*0.5f, centerPos.y + iconHeight*0.5f, 0);
posArray[2] = new Vector3(centerPos.x + iconWidth*0.5f, centerPos.y + iconHeight*0.5f, 0);
posArray[3] = new Vector3(centerPos.x + iconWidth*0.5f, centerPos.y - iconHeight*0.5f, 0);
// Log.Info("图标宽度={0},{1} ,中心点={2}",iconWidth,iconHeight,centerPos);
}
else
{
//Log.Info("uiName={0},渲染模式为Overlay",canvas.name);
trans.GetWorldCorners(posArray);
}
return posArray;
}
上面获取到图标四个点的世界坐标之后,可以计算出Tips的世界坐标,示例:
注:我使用的Tips的pivot是居中对齐的
local tipsWidth = self.retRoot.sizeDelta.x * self.canvas.transform.localScale.x
local tipsHeight = self.retRoot.sizeDelta.y * self.canvas.transform.localScale.y
printf("屏幕大小=", Screen.width, ",", Screen.height, " ,Tips宽度=", tipsWidth, ",", tipsHeight)
local posArray = LuaHelper.GetUIScreenPosition(canvas, rectTrans)
local tmpPos = posArray[1]
--for i = 0, posArray.Length-1 do
-- print(posArray[i])
--end
if posArray[1] then
if posArray[0].x - tipsWidth > 0 then
if posArray[1].y > tipsHeight then
print("在屏幕左上区域,顶对齐")
tmpPos = Vector3(posArray[0].x - tipsWidth * 0.5, posArray[1].y - tipsHeight * 0.5, 0)
else
print("在屏幕左下区域,底对齐")
tmpPos = Vector3(posArray[0].x - tipsWidth * 0.5, posArray[0].y + tipsHeight * 0.5, 0)
end
else
if posArray[1].y > tipsHeight then
print("在屏幕右上区域,顶对齐")
tmpPos = Vector3(posArray[2].x + tipsWidth * 0.5, posArray[1].y - tipsHeight * 0.5, 0)
else
print("在屏幕右下区域,底对齐")
tmpPos = Vector3(posArray[2].x + tipsWidth * 0.5, posArray[0].y + tipsHeight * 0.5, 0)
end
end
else
tmpPos = posArray[0]
end
self.retRoot.position = tmpPos
获取UI元素的实际大小
当在编辑器下开发时(或者设备分辨率和开发分辨率不相同时),Game区域大小并不是实际设置的分辨率大小,也就是说你从属性面板看到的Width和Height和图片实际的Size是有区别的。
那么如何获取某元素的实际大小呢?
//实际宽度= 宽度 * canvas的缩放值
var viewWidth = retRoot.sizeDelta.x * canvas.transform.localScale.x
网友评论