我有一张图像(png和svg),本质上是地图的符号。我想在符号上添加动态文本,以表示不同位置的值。我没有创建自定义Drawable并将其与xml混淆的经验,因此对于解决此问题的最佳方法感到有些困惑。
截至目前,我已经创建了这个drawable,它在Imageview上绘制了一个textview,但是由于文本视图需要垂直于图像中心偏移显示,因此我无法正确放置项目。我还需要ImageView来按比例调整到TextView的大小。
我认为下一步是获取TextView的高度和宽度,并强制ImageView大于这些尺寸。但是我该如何操纵textview的位置?
public class PricePinDrawable extends Drawable {
private final int DRAWABLE_SIZE = 32;
private final int DEFAULT_TEXT_SIZE = 12;
private final TextView textView;
private final ImageView imageView;
private final int intrinsicSize;
PricePinDrawable(@NonNull final Context context,
@NonNull final CharSequence text) {
intrinsicSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
DRAWABLE_SIZE,
context.getResources().getDisplayMetrics());
textView = createTextView(context, text);
imageView = createImageView(context);
}
private ImageView createImageView(Context context) {
final ImageView imageView = new ImageView(context);
final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
imageView.setLayoutParams(lp);
imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.price_pin));
imageView.measure(intrinsicSize,intrinsicSize);
imageView.layout(0,0, intrinsicSize,intrinsicSize);
return imageView;
}
private TextView createTextView(@NonNull final Context context,
@NonNull final CharSequence text) {
final TextView textView = new TextView(context);
final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER);
textView.setLines(1);
textView.setTextColor(Color.WHITE);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE);
textView.setText(text);
textView.setWidth((int)Math.round(intrinsicSize));
textView.setHeight((int)Math.round(intrinsicSize));
textView.measure(intrinsicSize,intrinsicSize);
textView.layout(0,0, intrinsicSize,intrinsicSize);
return textView;
}
public void setText(@NonNull final CharSequence text) {
textView.setText(text);
invalidateSelf();
}
@Override
public void draw(@NonNull final Canvas canvas) {
imageView.draw(canvas);
textView.draw(canvas);
}
@Override
public void setAlpha(final int alpha) {
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
}
@Override
public int getIntrinsicHeight() {
return intrinsicSize;
}
@Override
public int getIntrinsicWidth() {
return intrinsicSize;
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}