Situtation:如何实现图像蒙版?
我正在研究一个小应用程序,该应用程序应该使用户能够触发某些操作,具体取决于他们点击屏幕的哪一部分。想象一张泰迪熊的照片,如果你点击一个鼻子,它会显示“鼻子”。我所做的是将LayoutLayout放入一个LinearLayout。因为我必须覆盖不同的屏幕尺寸,所以我没有在xml布局文件中设置背景。
片段形式的xml:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="visible" >
<LinearLayout
android:id="@+id/viewThouShaltRespondToClicks"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:orientation="vertical"
android:longClickable="true"
android:visibility="visible" />
<!-- mask -->
<LinearLayout
android:id="@+id/viewInvisibleMask"
android:visibility="invisible"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</FrameLayout>
然后在活性的OnCreate事件予检查的显示分辨率和经由setBackgroundResource()设置适当的背景。我为每个分辨率准备了背景图像。
final Point QVGA = new Point(240,320); // portrait
// Obtain the screen resolution if the device
Display defaultDisplay = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point displayResolution = new Point(defaultDisplay.getWidth(), defaultDisplay.getHeight());
if (displayResolution.equals(QVGA))
{
viewThouShaltRespondToClicks.setBackgroundResource(R.drawable.image_to_be_clicked_upon_240x320);
viewInvisibleMask.setBackgroundResource(R.drawable.mask_240x320);
}
else if ... // check for another resolution
即使资源中的图像的尺寸不正确,它也会被拉伸/缩小为屏幕尺寸。只要背景图像的宽高比与显示比例相似并且所得图像不太重要,就可以。但是有一个问题,下面解释。
要检测哪个区域被点击,该区域本身可能是不规则的形状,我采取了以下方法。我创建一个与背景图像具有相同尺寸的图像蒙版(bmp),只有它具有白色背景并且可点击区域的颜色不同。颜色标识该区域。我所要做的就是获取点击事件的坐标(这里没有问题),进入蒙板图像并读取坐标上的像素颜色。问题是,蒙版图像的大小不正确。在我的设备上它被设置为1200x700,但我想它在其他设备上占用一些任意大小。
第一个问题:是否有办法以某种方式说服不可见的布局加载背景图像,然后伸展/缩小它显示大小,因为它本身发生可见布局?
另一种方法是将掩膜图像(bmp,png)加载到某些内存结构中并调整其大小以显示大小。 我已经试过的东西,如:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false; // do not scale
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmapMask = BitmapFactory.decodeResource(this.getResources(), R.drawable.mask, options);
// on this place stretch shrink should follow but I have no idea how
但我不知道如何扩展位图到适当的大小。
有什么建议吗?
细心的读者会注意到我已经做了一个隐藏的遮罩视图。问题是背景图像会假设任意大小(在我的情况下为1200x700),这与实际视图大小不符。 getPixel()方法也是我所知道的。问题是,我不知道如何缩放位图到合适的大小。 – Anderson 2011-12-14 13:13:30