提问人:Eddie Piña 提问时间:7/12/2023 最后编辑:shingoEddie Piña 更新时间:7/14/2023 访问量:21
尝试在 iOS 和某些 Android 设备上裁剪图像并返回错误的位置
Trying to Crop an Image on iOS and some Android devices and returns with wrong position
问:
private IEnumerator CropImage(Texture original, int width, int height)
{
yield return new WaitForEndOfFrame();
float originalWidth = original.width;
float originalHeight = original.height;
float originalAspectRatio = originalWidth / originalHeight;
float targetAspectRatio = (float)width / (float)height;
float scaleFactor;
if (originalAspectRatio >= targetAspectRatio)
{
// Image is wider than frame. Use height to determine scale.
scaleFactor = height / originalHeight;
Debug.Log("[Image Editor]: Image is wider than frame. Scale Factor: " + scaleFactor);
}
else
{
// image is taller than frame. Use width to determine scale
scaleFactor = width / originalWidth;
Debug.Log("[Image Editor]: Image is taller than frame. Scale Factor: " + scaleFactor);
}
int newWidth = Mathf.FloorToInt(originalWidth * scaleFactor * _zoomScale);
int newHeight = Mathf.FloorToInt(originalHeight * scaleFactor * _zoomScale);
RenderTexture rTex = new RenderTexture(newWidth, newHeight, 24, RenderTextureFormat.ARGB32);
Graphics.Blit(original, rTex);
Texture2D newTex = new Texture2D(width, height, TextureFormat.RGB24, false);
RenderTexture.active = rTex;
Vector2 imagePositions = m_Image.rectTransform.localPosition;
float xPos = (newWidth - width) * 0.5f - imagePositions.x;
float yPos = (newHeight - height) * 0.5f + imagePositions.y;
newTex.ReadPixels(new Rect(new Vector2(xPos, yPos), m_Image.rectTransform.rect.size), 0, 0);
//newTex.ReadPixels(new Rect(xPos, yPos, ImageContainer.rect.width, ImageContainer.rect.height), 0, 0);
yield return new WaitForEndOfFrame();
newTex.Apply();
finalTex = newTex;
m_CroppedImage.texture = finalTex;
_data.OnSetImage?.Invoke(finalTex);
UIManager.Inst.RemoveTopModal();
}
您好,我有这段代码可以裁剪图像并在编辑器和 android 中运行良好,但由于某种原因,在 iOS 和某些 Android 设备中它显示了错误的位置。有人知道为什么会这样吗?我看到 RenderTexture 过去有一些错误,但我不知道到底发生了什么
我尝试了具有不同形式的 ReadPixels 和我想要的尺寸,但目前我什么也找不到。我希望你能帮助我。
答:
0赞
Eddie Piña
7/14/2023
#1
解决。 我已经发现了这个问题,当我说图形 API 的提供时,我是对的。感谢 Bunny 帮助我意识到这一点。我必须验证我使用的图形 API
如果您有更干净的东西来验证这一点,请与我分享。
float xPos = ((newWidth - width) * 0.5f) - ImageContainer.anchoredPosition.x;
float yPos = ((newHeight - height) * 0.5f) + ImageContainer.anchoredPosition.y;
if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLCore || SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2 || SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3 ||SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Metal)
{
yPos = ((newHeight - height) * 0.5f) + (1 - ImageContainer.anchoredPosition.y);
}
评论