Uiautomator中獲取屏幕座標/控件顏色RGB值

在實際測試中有時候會遇到一些開關按鈕,但是這些按鈕的checkable屬性爲false,很難從控件屬性上判定開關狀態的時候,我們可以根據開關的當前顏色來判定。

比如:

所以,這就需要獲取控件的座標的顏色值,隨後通過顏色值來判定開關狀態。

    /**
	 * 獲取給定圖片的指定座標點的RGB值,結果以16進制輸出(例:ffffff)
	 *
	 * @param picPath 需要獲取像素點的圖片地址
	 * @param x       像素點的橫座標值
	 * @param y       像素點的縱座標值
	 * @return 16進制的RGB值,以String類型返回。例:ffffff
	 * @throws AutoException
	 * @author ZeKyll
	 */
	public String getRGB(String picPath, int x, int y) throws AutoException {
		LogTimeGetter.updateTimeString();
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inPreferredConfig = Bitmap.Config.ARGB_8888;
		Bitmap targetBitmap = BitmapFactory.decodeFile(picPath, op);
		int rgbPixel = targetBitmap.getPixel(x, y);
		// 轉換字符
		String r1 = Integer.toHexString(Color.red(rgbPixel));
		String g1 = Integer.toHexString(Color.green(rgbPixel));
		String b1 = Integer.toHexString(Color.blue(rgbPixel));
		String colorStr = r1 + g1 + b1;
//		Log.i("Value--------",colorStr);
		TestReport.i(LOGTAG, "獲取圖片座標點(" + "x-" + x + ",y-" + y + ")RGB值:" + colorStr);
		return colorStr;
	}
	/**
	 * 獲取當前界面中指定座標點的RGB值,結果以16進制輸出(例:ffffff)
	 * @param x       像素點的橫座標值
	 * @param y       像素點的縱座標值
	 * @return 16進制的RGB值,以String類型返回。例:ffffff
	 * @throws AutoException
	 * @author ZeKyll
	 */
	public String getRGB(int x, int y) throws AutoException {
		LogTimeGetter.updateTimeString();
		String retRGB = "";
		String imageFileName=screenshotTaker.takeScreenshot("_RGB");
		File file = new File(imageFileName);
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inPreferredConfig = Bitmap.Config.ARGB_8888;
		Bitmap targetBitmap = BitmapFactory.decodeFile(imageFileName, op);
		int rgbPixel = targetBitmap.getPixel(x, y);
		// 轉換字符
		String r1 = Integer.toHexString(Color.red(rgbPixel));
		String g1 = Integer.toHexString(Color.green(rgbPixel));
		String b1 = Integer.toHexString(Color.blue(rgbPixel));
		String colorStr = r1 + g1 + b1;
//		Log.i("Value--------",colorStr);
		TestReport.i(LOGTAG, "獲取當前屏幕座標點(" + "x-" + x + ",y-" + y + ")RGB值:" + colorStr);
		if (file.exists()){
			file.delete();
		}
		return colorStr;
	}



    /***
	 * 截屏後直接保存在savepath下
	 * 
	 * @param savename 截圖文件名稱
	 * @return 保存的截圖文件的絕對路徑
	 * @author ZeKyll
	 */
	public String takeScreenshot(String savename)
	{
		savename=df.format(new Date())+savename;
		LogTimeGetter.updateTimeString();
		screenshortDevice.takeScreenshot(new File(savepath+savename+".png"));
		return savepath+savename+".png";
	}

說明:這裏獲取的顏色值爲一張圖片中的一個座標點,所以,需要給一張圖片。第一個方法是自動截當前界面的圖片,第二個是傳遞圖片地址參數進入方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章