如何在Xamarin Android中合并两张图片并实现类似iOS CGRect的定位?
Got it, let's solve this image merging and positioning challenge you're dealing with. Since you've already successfully loaded your two bitmaps from resources, we're just a few steps away from getting this done.
核心思路
On Android, we use Canvas to draw one bitmap onto another, and RectF is the direct equivalent of iOS's CGRect for positioning. Here's a step-by-step breakdown:
1. 确保背景图可编辑
First, bitmaps loaded via BitmapFactory.DecodeResource are usually immutable by default. We need to create a mutable copy so we can draw our object image onto it:
// Convert background bitmap to editable mutable version Bitmap mutableBackground = TheBackGroundImage.Copy(Bitmap.Config.Argb8888, true);
2. 使用Canvas合并图片 + RectF定位
Now we'll use Canvas to draw the object image onto the background at your desired position. RectF(left, top, right, bottom) maps exactly to iOS's CGRect(x, y, width, height)—since right = left + width and bottom = top + height.
Example: Basic positioning (fixed coordinates)
using (Canvas canvas = new Canvas(mutableBackground)) { // Define position: place object at (100, 200) with original size float posX = 100f; float posY = 200f; float objWidth = TheObjectImage.Width; float objHeight = TheObjectImage.Height; // Create RectF (matches iOS CGRect) RectF objectPosition = new RectF(posX, posY, posX + objWidth, posY + objHeight); // Draw the object bitmap onto the background at the defined position canvas.DrawBitmap(TheObjectImage, null, objectPosition, null); } // mutableBackground now holds your merged image—use it for ImageView or save to storage
Example: Scale the object image
If you need to resize the object (like adjusting CGRect's width/height), just modify the RectF bounds:
// Scale object to 50% of original size float scaledWidth = TheObjectImage.Width * 0.5f; float scaledHeight = TheObjectImage.Height * 0.5f; RectF scaledPosition = new RectF(posX, posY, posX + scaledWidth, posY + scaledHeight); canvas.DrawBitmap(TheObjectImage, null, scaledPosition, null);
Example: Center the object on the background
To center the object (a common use case), calculate the position dynamically:
float centerX = (mutableBackground.Width - TheObjectImage.Width) / 2f; float centerY = (mutableBackground.Height - TheObjectImage.Height) / 2f; RectF centeredPosition = new RectF(centerX, centerY, centerX + TheObjectImage.Width, centerY + TheObjectImage.Height); canvas.DrawBitmap(TheObjectImage, null, centeredPosition, null);
3. 内存注意事项
Bitmaps are memory-heavy, so don't forget to recycle the original immutable bitmaps once you're done with them to avoid leaks:
TheBackGroundImage.Recycle(); TheObjectImage.Recycle();
内容的提问来源于stack exchange,提问作者Carlos Rodrigez

