2015-09-01 48 views
1

我想進入渲染腳本,並對分配使用感到困惑。幾乎所有的例子表明未來的算法:從位圖Renderscript分配

  1. 創建In和Out位圖
  2. 從位圖和註銷相應
  3. 配置腳本創建和註銷分配和輸出分配進行的forEach方法
  4. 拷貝結果進位圖使用CopyTo方法

類似的東西:

Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena); 
    Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig()); 

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap); 
    Allocation allocationOut = Allocation.createFromBitmap(renderScript, dstBitmap); 

    scriptColorMatrix.setGreyscale(); 

    scriptColorMatrix.forEach(allocationIn, allocationOut); 

    //no difference after removing this line 
    allocationOut.copyTo(dstBitmap); 

    imagePreview.setImageBitmap(dstBitmap); 

這工作,但它也有效,即使我省略步驟4通過去除:

allocationOut.copyTo(dstBitmap); 

讓我們去進一步和較低的亮度灰度後:

Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena); 
    Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig()); 

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap); 
    Allocation allocationOut = Allocation.createFromBitmap(renderScript, dstBitmap); 

    scriptColorMatrix.setGreyscale(); 

    scriptColorMatrix.forEach(allocationIn, allocationOut); 

    //reset color matrix 
    scriptColorMatrix.setColorMatrix(new Matrix4f()); 

    //adjust brightness 
    scriptColorMatrix.setAdd(-0.5f, -0.5f, -0.5f, 0f); 

    //Performing forEach vise versa (from out to in) 
    scriptColorMatrix.forEach(allocationOut, allocationIn); 

    imagePreview.setImageBitmap(srcBitmap); 

不久描述上面的代碼中,我們從In分配到Out 1執行灰度collor矩陣,並向後調整亮度。我從來沒有調用過copyTo方法,但最後我在srcBitmap中得到了結果,它是正確的。

這不是結束。讓我們更深入。我將只留下一個位圖和一個分配:

Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lena); 

    Allocation allocationIn = Allocation.createFromBitmap(renderScript, srcBitmap); 

    scriptColorMatrix.setGreyscale(); 

    scriptColorMatrix.forEach(allocationIn, allocationIn); 

    //reset color matrix 
    scriptColorMatrix.setColorMatrix(new Matrix4f()); 

    //adjust brightness 
    scriptColorMatrix.setAdd(-0.5f, -0.5f, -0.5f, 0f); 

    scriptColorMatrix.forEach(allocationIn, allocationIn); 

    imagePreview.setImageBitmap(srcBitmap); 

的結果是一樣的...



任何人都可以解釋爲什麼它會發生,在哪裏使用CopyTo從哪裏我可以使用目標沒有它的位圖?

回答

6

Allocation對象是需要的,以便將Bitmap正確映射到Renderscript理解的內容。如果您的目標是API 18或更高版本,則您使用的Allocation.createFromBitmap()方法會自動給出標誌USAGE_SHARED,該標誌試圖使AllocationBitmap對象使用相同的後備內存。所以這兩個是鏈接但技術上仍然需要copyTo()方法,因爲RS實現可能需要將其同步回來。在某些平臺上,這可能已經發生,其他人可能會導致暫停,因爲DMA或其他機制正在更新Bitmap的後備存儲器,並且RS代碼進行了任何更改。

至於爲什麼你可以在調用腳本時反轉輸入/輸出Allocation順序 - 這是有效的,並且取決於你的參數和順序是否正確。對於RS,它們只是指向某種類型的後臺數據進行操作的對象。由於兩者都是使用Allocation.createFromBitmap()調用創建的,因此只要Bitmap對象可變,它們就可以用作輸入或輸出。

同樣,使用相同的Allocation進行輸入輸出不正常,但也無效。這隻意味着您的輸入正在變化。只要您的腳本沒有在數據中訪問其他Element s,那麼當根函數調用特定的Element時,它應該可以工作(如您所見)。

+0

非常感謝!這是非常明確的答案 – VinSmile

+0

你非常歡迎!我很高興你發現它有幫助! –