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); 
相關問題