यह उदाहरण दर्शाता है कि Kotlin का उपयोग करके Android में इमेज पर टेक्स्ट कैसे ड्रॉ (लिखा) जाता है। RelativeLayout का उपयोग करके ImageView के ऊपर TextView को ओवरले किया जाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio खोलें, File → New Project पर जाएं और नया प्रोजेक्ट बनाने के लिए सभी आवश्यक विवरण भरें।
चरण 2: activity_main.xml में ओवरले लेआउट बनाएं
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16sp"
android:padding="4dp"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
चरण 3: MainActivity.kt में टेक्स्ट सेट करें
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val textView: TextView = findViewById(R.id.text)
textView.text = "Into the wild!"
textView.setTextColor(Color.WHITE)
}
}
चरण 4: AndroidManifest.xml कॉन्फ़िगर करें
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ऐप चलाएं
अपने Android डिवाइस को कंप्यूटर से कनेक्ट करें। Android Studio में किसी एक्टिविटी फ़ाइल को खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और ऐप चलने पर डिफ़ॉल्ट स्क्रीन देखें।
उन्नत विकल्प: यदि आपको वास्तव में बिटमैप पर टेक्स्ट ड्रॉ करना है (लेयर के रूप में नहीं), तो Canvas और Paint का उपयोग करें:
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image).copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
val paint = Paint().apply {
color = Color.WHITE
textSize = 48f
isAntiAlias = true
}
canvas.drawText("Into the wild!", 50f, 100f, paint)
imageView.setImageBitmap(bitmap)