0

enter image description hereAndroid的画布在三角形

在这个图片我希望文字完全是与CYAN颜色的三角形绘制文本。
我已经创建了自己的ImageView

public class BookImageView extends android.support.v7.widget.AppCompatImageView { 

private static final Float DISCOUNT_SIDE_SIZE = 0.33333F; 

private Bitmap bitmap; 

private Paint drawPaint = new Paint(); 
private Paint trianglePaint = new Paint(); 

{ 
    trianglePaint.setColor(Constants.DISCOUNT_COLOR); 
    trianglePaint.setStyle(Paint.Style.FILL); 
    trianglePaint.setShadowLayer(10.0f, 10.0f, 10.0f, Color.parseColor("#7f000000")); 
    trianglePaint.setAntiAlias(true); 

    drawPaint.setColor(Color.BLACK); 
    drawPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); 
    drawPaint.setShadowLayer(1f, 0f, 1f, Color.BLACK); 
} 

// Constractors ...  

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    if (bitmap != null) { 
     Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565); 
     Canvas tempCanvas = new Canvas(tempBitmap); 
     tempCanvas.drawBitmap(bitmap, 0, 0, null); 

     Path path = new Path(); 
     path.setFillType(Path.FillType.EVEN_ODD); 

     float size = bitmap.getWidth() * DISCOUNT_SIDE_SIZE; 

     path.lineTo(size, 0); 
     path.lineTo(0, size); 
     path.lineTo(0, 0); 
     path.close(); 

     tempCanvas.drawPath(path, trianglePaint); 

     float scale = getResources().getDisplayMetrics().density; 

     drawPaint.setTextSize((int) (14 * scale)); 

     Rect textBounds = new Rect(); 
     drawPaint.getTextBounds("50%", 0, "50%".length(), textBounds); 
     int x = (int) (size/2) - textBounds.width()/2; 
     int y = (int) (size/2) - textBounds.height()/2; 

     tempCanvas.save(); 
     tempCanvas.rotate(-45, x, y); 
     tempCanvas.drawText("50%", x, y, drawPaint); 
     tempCanvas.restore(); 

     setImageDrawable(new BitmapDrawable(getContext().getResources(), tempBitmap)); 
    } 
} 

@Override 
public void setImageBitmap(Bitmap bitmap) { 
    this.bitmap = bitmap; 
    invalidate(); 
} 

}

我能做些什么来解决这个问题?

+0

减小文本大小? –

+0

尝试在非旋转的三角形中绘制,然后将整个视图旋转45度 –

+0

@SunnyKumarAditya感谢您的回答。但不起作用 –

回答

1

你可以尝试这样的事情

1)测量您的文本的宽度 使用measureText

2)从您绘制计算剩余宽度点绘制

3)现在取决于使用情况,您可以缩短文本的长度或根据需要缩放文本

int textWidthRequired = (int) drawPaint.measureText(textToDraw); 
    int widthRemainingToDraw = totalWidth/2 - textDrawX; 
    if(textWidthRequired > widthRemainingToDraw){ 
     //handling 
    } 
    // draw text 
    tempCanvas.drawText(textToDraw,textDrawX, textDrawY, drawPaint);