【发布时间】:2014-01-13 09:20:34
【问题描述】:
我在 imageView 中使用 .png 图像,但仍显示方形透明背景。我想从 imageView 中删除所有多余的空格。即使在 imageView 中使用 .png 图像,字符之间的额外空格仍然存在。我想为图像着色,所以不希望有多余的空间。在附加的图像中,“3”内的空白处的点击事件是我不想要的。我只想让点击事件在“3”上起作用。
这是我的 XML。里面没有什么。另外图中“3”周围的方块是用paint而不是代码绘制的,只是为了澄清mu问题。 imageView有一个方形边框,我想根据“3”来匹配它
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/image"
android:id="@+id/test_image"
android:scaleType="matrix"
android:background="@null"
android:text="@string/hello_world" />
</RelativeLayout>
我尝试了 ramaral 的解决方案。它的工作原理更接近于所需,但不是很准确。如果我上色非常慢,效果会很好,但如果我开始更快地移动手指,那么空白区域也会上色。这是我正在使用的代码
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) this.findViewById(R.id.test_image);
BitmapFactory.Options decode_options = new BitmapFactory.Options();
decode_options.inMutable = true;
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image,decode_options);
canvas = new Canvas(bitmap);
paint = new Paint();
transparentPaint = new Paint();
transparentPaint.setColorFilter(new PorterDuffColorFilter(android.graphics.Color.TRANSPARENT, PorterDuff.Mode.SRC_ATOP));
transparentPaint.setStrokeWidth(5);
paint.setColorFilter(new PorterDuffColorFilter(android.graphics.Color.GREEN, PorterDuff.Mode.SRC_ATOP));
paint.setStrokeWidth(5);
imageView.setScaleType(ScaleType.MATRIX);
imageView.setImageBitmap(bitmap);
imageView.setOnTouchListener(this);
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downx = event.getX();
downy = event.getY();
break;
case MotionEvent.ACTION_MOVE:
upx = event.getX();
upy = event.getY();
Drawable imgDrawable = ((ImageView)v).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
int color = bitmap.getPixel((int)upx, (int)upy);
if ((color & 0xff000000) == 0x0){//pixel is TRANSPARENT
canvas.drawLine(downx, downy, upx, upy, transparentPaint);
imageView.invalidate();
downx = upx;
downy = upy;
return true;
}else {
canvas.drawLine(downx, downy, upx, upy, paint);
imageView.invalidate();
downx = upx;
downy = upy;
return true;
}
case MotionEvent.ACTION_UP:
upx = event.getX();
upy = event.getY();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
这是这段代码的输出。我在代码中使用的图像是简单的“3”,一个 .png 图像,除了 3 之外的区域是透明的。
【问题讨论】:
-
你可以发布xml代码吗?
-
我已经用 xml 代码更新了我的问题