Hello,
I have this piece of code that crops an image and works well in the editor and android, but for some reason in iOS and some Android devices it shows a wrong position. Anyone know why this happen? I saw that RenderTexture have some bugs in the past but I don’t know exactly what is happening
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();
}