最终找到了一个合适的解决方案,可以跨不同的 Android 版本/ROM/风格进行扩展。
The main problem is that the EditText's background drawable itself has transparent padding:
![enter image description here](https://i.stack.imgur.com/ivW6c.png)
另外,我注意到这种透明填充有所不同a lot不同 Android 版本/ROM/样式之间的差异(例如,库存 ICS 根本没有透明填充)。
总而言之,我的原始代码将 ImageView 与 EditText 正确对齐。然而,我真正想要的是使我的 ImageView 与visibleEditText 背景的一部分。
为了实现这一点,我扫描了从 EditText 的背景可绘制对象创建的位图。我从上到下和从下到上扫描它以找到完全透明线的数量,并将这些值用作我的 ImageView 的顶部/底部填充。在我的 N1 上,所有这一切持续花费的时间不到 5 毫秒。这是代码:
if(editor.getBackground() != null) {
int width = editor.getWidth();
int height = editor.getHeight();
Drawable backgroundDrawable = editor.getBackground().getCurrent();
// Paint the editor's background in our bitmap
Bitmap tempBitmap = Bitmap.createBitmap(width, height, Config.ARGB_4444);
backgroundDrawable.draw(new Canvas(tempBitmap));
// Get the amount of transparent lines at the top and bottom of the bitmap to use as padding
int topPadding = countTransparentHorizontalLines(0, height, tempBitmap);
int bottomPadding = countTransparentHorizontalLines(height-1, -1, tempBitmap);
// Discard the calculated padding if it means hiding the image
if(topPadding + bottomPadding > height) {
topPadding = 0;
bottomPadding = 0;
}
tempBitmap.recycle();
// Apply the padding
image.setPadding(0, topPadding, 0, bottomPadding);
}
private int countTransparentHorizontalLines(int fromHeight, int toHeight, Bitmap bitmap) {
int transparentHorizontalLines = 0;
int width = bitmap.getWidth();
int currentPixels[] = new int[width];
boolean fullyTransparentLine = true;
boolean heightRising = (fromHeight < toHeight);
int inc = heightRising ? 1 : -1;
for(int height = fromHeight; heightRising ? (height < toHeight) : (toHeight < height); height+=inc) {
bitmap.getPixels(currentPixels, 0, width, 0, height, width, 1);
for(int currentPixel : currentPixels) {
if(currentPixel != Color.TRANSPARENT && Color.alpha(currentPixel) != 255) {
fullyTransparentLine = false;
break;
}
}
if(fullyTransparentLine)
transparentHorizontalLines++;
else
break;
}
return transparentHorizontalLines;
}
它就像一个魅力!
![it works!](https://i.stack.imgur.com/do9tK.png)