2010-10-20 64 views

回答

1

這是不可能使用正常的命中測試功能,因爲你發現與MSDN的參考。

我唯一的想法是將您的圖像轉換爲WritableBitmap類,並使用Pixels屬性進行alpha通道命中測試。我實際上沒有嘗試過這一點,我無法想象這是微不足道的,但它應該在理論上起作用。

像素是一個大的int [],每個整數的4個字節對應ARGB。它使用預乘ARGB32格式,因此如果除了完整255之外還有任何alpha透明度,其他RGB值將相應縮放。我假設你想要的任何東西全字母被認爲是一個「打」,所以你可以只覈對阿爾法字節,看它是否是255

你會訪問你正在尋找的行/列像素通過數組索引檢查是這樣的:

int pixel = myBitmap.Pixels[row * myBitmap.PixelWidth + col]; 

退房this post一些更多的想法。

編輯:

我扔一起快速測試,它的工作原理,它是非常簡單的:

public MainPage() 
{ 
    InitializeComponent(); 

    this.image = new BitmapImage(new Uri("my_tranny_image.png", UriKind.Relative)); 
    this.MyImage.Source = image; 

    this.LayoutRoot.MouseMove += (sender, e) => 
    { 
     bool isHit = ImageHitTest(image, e.GetPosition(this.MyImage)); 
     this.Result.Text = string.Format("Hit Test Result: {0}", isHit); 
    }; 
} 

bool ImageHitTest(BitmapSource image, Point point) 
{ 
    var writableBitmap = new WriteableBitmap(image); 

    // check bounds 
    if (point.X < 0.0 || point.X > writableBitmap.PixelWidth - 1 || 
     point.Y < 0.0 || point.Y > writableBitmap.PixelHeight - 1) 
     return false; 

    int row = (int)Math.Floor(point.Y); 
    int col = (int)Math.Floor(point.X); 

    int pixel = writableBitmap.Pixels[row * writableBitmap.PixelWidth + col]; 
    byte[] pixelBytes = BitConverter.GetBytes(pixel); 

    if (pixelBytes[0] != 0x00) 
     return true; 
    else 
     return false; 
} 

你可能會想做出一些優化,例如不能在每一個MouseMove事件創建WritableBitmap但這只是一個概念證明,表明它的工作原理。

+0

我曾經想過要做那樣的事情,但它似乎不必要的複雜,所以我想確保沒有更簡單的解決方案。我遇到的另一種方法嘗試使用對象輪廓來創建路徑幾何體,然後檢查鼠標點擊是否在內。這也適用於我的應用程序,但對於這樣一個基本問題似乎又太複雜了。 – cfroehlich 2010-10-20 16:22:50

+0

是否有多個PNG或只有一個?我不認爲這會很糟糕,我猜測你正在測試MouseMove事件,所以你只有一個點轉換爲圖像座標,然後檢查X和Y對像素行和列。路徑幾何對我而言聽起來更加複雜。 – 2010-10-20 18:15:38

+0

用一些示例代碼編輯我的答案。 – 2010-10-20 20:33:50

相關問題