簡體   English   中英

如何在圖像上繪制文本?

[英]How to draw text On image?

我想在圖像上繪制文本(用於用文本保存該圖像)。 我有圖像視圖我將位圖設置為該圖像我想在圖像上繪制文本(用戶輸入的文本)。 我在保存之前試過這個.....

void saveImage() {
    File myDir=new File("/sdcard/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

xml代碼是..

<FrameLayout 
     android:id="@+id/framelayout"
     android:layout_marginTop="30dip"
     android:layout_height="fill_parent" 
     android:layout_width="fill_parent">

     <ImageView 
          android:id="@+id/ImageView01"
          android:layout_alignParentTop="true"
          android:layout_height="wrap_content" 
          android:layout_width="wrap_content"/>

     <TextView android:id="@+id/text_view2"
          android:layout_marginTop="20dip"
          android:layout_width="wrap_content" 
          android:text="SampleText"
          android:textSize="12pt"
          android:layout_alignTop="@+id/ImageView01" 
          android:layout_height="wrap_content"/>  

</FrameLayout>

按照Vladislav Skoumal 的建議,試試這個方法:

public Bitmap drawTextToBitmap(Context mContext,  int resourceId,  String mText) {
    try {
         Resources resources = mContext.getResources();
         float scale = resources.getDisplayMetrics().density;
         Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
         android.graphics.Bitmap.Config bitmapConfig =   bitmap.getConfig();
         // set default bitmap config if none
         if(bitmapConfig == null) {
           bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
         }
         // resource bitmaps are imutable,
         // so we need to convert it to mutable one
         bitmap = bitmap.copy(bitmapConfig, true);

         Canvas canvas = new Canvas(bitmap);
         // new antialised Paint
         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
         // text color - #3D3D3D
         paint.setColor(Color.rgb(110,110, 110));
         // text size in pixels
         paint.setTextSize((int) (12 * scale));
         // text shadow
         paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

         // draw text to the Canvas center
         Rect bounds = new Rect();
         paint.getTextBounds(mText, 0, mText.length(), bounds);
         int x = (bitmap.getWidth() - bounds.width())/6;
         int y = (bitmap.getHeight() + bounds.height())/5;

         canvas.drawText(mText, x * scale, y * scale, paint);

         return bitmap;
    } catch (Exception e) {
        // TODO: handle exception

        return null;
    }

}

調用這個方法

Bitmap bmp =drawTextToBitmap(this,R.drawable.aa,"Hello Android");
img.setImageBitmap(bmp);

輸出

在此處輸入圖片說明

更新了 SaveImage() 方法,以支持文本繪制。

void saveImage() {
    File myDir=new File("/sdcard/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
        FileOutputStream out = new FileOutputStream(file);

        // NEWLY ADDED CODE STARTS HERE [
            Canvas canvas = new Canvas(originalBitmap);

            Paint paint = new Paint();
            paint.setColor(Color.WHITE); // Text Color
            paint.setTextSize(12); // Text Size
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
            // some more settings...

            canvas.drawBitmap(originalBitmap, 0, 0, paint);
            canvas.drawText("Testing...", 10, 10, paint);
        // NEWLY ADDED CODE ENDS HERE ]

        originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
       e.printStackTrace();
    }
}

讓我知道這是否適合您。

沙什

  1. 創建一個空位圖
  2. 創建一個新的 Canvas 對象並將這個位圖傳遞給它
  3. 調用 view.draw(Canvas) 將您剛剛創建的畫布對象傳遞給它。 有關詳細信息,請參閱方法文檔。
  4. 使用 Bitmap.compress() 將位圖的內容寫入 OutputStream,可能是文件。

偽代碼:

Bitmap  bitmap = Bitmap.createBitmap(200,200,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText();
//necessary arguments and draw whatever you want. thes all are drawn on the bitmap.finally save this bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 

您可以擴展視圖以創建自定義視圖。 就像是

public class PieView extends View { 
    public PieView(Context context) {
        super(context);
        overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.piechart_shade, 
        null);
        overlayWidth  = overlayBitmap.getWidth();
        setLayoutParams(new LayoutParams(overlayWidth, overlayWidth));      
    }

    @Override     
    protected void onDraw(Canvas canvas) {      
        super.onDraw(canvas);
    }
}

在 ondraw 方法中,您可以使用 canvas.drawBitmap 和 canvas.drawText 來繪制位圖和文本。

這樣您就不需要框架布局,因為一切都在一個自定義視圖中。

您可以將其包含在您的 xml 文件中

<com.raj.PieView android:id="@+id/framelayout" android:layout_marginTop="30dip"      
    android:layout_height="fill_parent" android:layout_width="fill_parent"/>

我解決了這個問題(不可變文件),但文件中沒有寫入任何內容...按照我的代碼:public static File writeOnImage(File file) throws IOException {

    Bitmap originalBitmap = BitmapFactory.decodeFile(file.getPath());
    originalBitmap = convertToMutable(originalBitmap);
    FileOutputStream out = new FileOutputStream(file);

    try {
        Canvas canvas = new Canvas(originalBitmap);

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(12);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        canvas.drawBitmap(originalBitmap, 0, 0, paint);
        canvas.drawText("Testing...", 10, 10, paint);

        originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}

如果您使用 Glide 獲取圖像,我修改了@Dwivedi 對此的回答(使用 kotlin):

Glide.with(this)
        .asBitmap()
        .load("https://images.pexels.com/photos/1387577/pexels-photo-1387577.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")
        .into(object : CustomTarget<Bitmap>() {
            override fun onLoadCleared(placeholder: Drawable?) {}

            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                val bm = resource.copy(Bitmap.Config.ARGB_8888, true)
                val tf = Typeface.create("Helvetica", Typeface.BOLD)

                val paint = Paint()
                paint.style = Paint.Style.FILL
                paint.color = Color.WHITE
                paint.typeface = tf
                paint.textAlign = Paint.Align.LEFT
                paint.textSize = dip(25).toFloat()

                val textRect = Rect()
                paint.getTextBounds("HELLO WORLD", 0, "HELLO WORLD".length, textRect)

                val canvas = Canvas(bm)

                //If the text is bigger than the canvas , reduce the font size
                if (textRect.width() >= canvas.width - 4)
                //the padding on either sides is considered as 4, so as to appropriately fit in the text
                    paint.textSize = dip(12).toFloat()

                //Calculate the positions
                val xPos = canvas.width.toFloat()/2 + -2

                //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
                val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + 0

                canvas.drawText("HELLO WORLD", xPos, yPos, paint)

                binding.imageDrawable.setImageBitmap(bm)
            }

        })

在圖像上增加文本視圖。 有關基本示例,請參閱http://www.android10.org/index.php/forums/43-view-layout-a-resource/715-tutorial-android-xml-view-inflation 這應該是最簡單的方法。

LinearLayout lLayout;

lLayout = (LinearLayout)findViewById(R.id.layout1);

layout1 is the main layout.

final LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

TextView tv = (TextView)inflater.inflate(R.layout.text, null);

lLayout.addView(tv);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM