Android: Drawing rectangular imageViews over existing image - java

I am making an Android app and attempting to programatically draw some clickable, rectangular blocks with text on one of two custom views contained in a ScrollLayout. The XML for my ScrollLayout looks like this:
<ScrollView
android:layout_width="match_parent"
android:id="#+id/calendarGridContainerView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/employeeSpinnerContainer"
android:paddingBottom="72dp"
android:layout_height="match_parent"
android:overScrollMode="never"
android:fillViewport="true"
android:elevation="1dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:id="#+id/schedule_view_container"
android:layout_height="wrap_content">
<FrameLayout
android:layout_height="wrap_content"
android:id="#+id/schedule_time_frame"
android:layout_width="100dp"
android:layout_alignParentTop="false"
android:layout_weight="0.5">
<include
layout="#layout/schedule_time_view"
android:layout_height="wrap_content"
android:layout_width="100dp" />
</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/schedule_grid_frame"
android:minHeight="179dp"
android:layout_toRightOf="#+id/schedule_time_frame"
android:layout_centerHorizontal="false"
android:layout_weight="8">
<include
layout="#layout/schedule_grid_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
</LinearLayout>
</ScrollView>
Note that the layout called scheduleGridLayout is where I am trying to draw these rectangles. It has the following XML:
<?xml version="1.0" encoding="utf-8"?>
<(package).ScheduleGridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:scheduleGridLayout="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
</(package).ScheduleGridLayout>
(When copying the above code, I removed the package name.)
In the constructor for ScheduleGridLayout.java, I call this.setWillNotDraw(false);. Before drawing the rectangles, I draw some horizontal gridlines on ScheduleGridLayout through its overridden onDraw() method:
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.LTGRAY);
final int width = getWidth();
final int rowHeight = ScheduleTimeLayout.SCHEDULE_VIEW_ROW_HEIGHT + ScheduleTimeLayout.TIME_LABEL_HEIGHT;
for(int i = 0; i < ScheduleTimeLayout.TIME_SEGMENT_COUNT + 1; i++){
if ((i % (int)(1.0/ScheduleTimeLayout.SEGMENT_SIZE)) == 0){
paint.setColor(Color.GRAY);
paint.setStrokeWidth((float)4.0);
}
else{
paint.setColor(Color.LTGRAY);
paint.setStrokeWidth((float)2.0);
}
int y = 178 + (int)(i*(rowHeight + 1) - rowHeight/2.0);
canvas.drawLine(0, y, width, y, paint);
}
Since I want the rectangles to be clickable, I have to add them as some sort of views rather than simply drawing their images onto the canvas. I've tried a few different ways to draw the rectangles-- currently I try to do it in onFinishInflate() in ScheduleGridLayout.java, like so:
Bitmap bmp = Bitmap.createBitmap(60,200,Bitmap.Config.RGB_565);
Bitmap tempBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
paint = new Paint();
paint.setColor(Color.RED);
tempCanvas.drawBitmap(bmp, 0, 0, null);
tempCanvas.drawRoundRect(new RectF(0,0,600,600), 2, 2, paint);
ImageView testBlock = new ImageView(getContext());
testBlock.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));
addView(testBlock);
However, there the block does not appear when I do this.
In a separate attempt, I tried creating an XML layout file for the schedule block:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<com.dalc.dalccalendar.ScheduleBlock
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:scheduleGridLayout="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/schedule_block">
</com.dalc.dalccalendar.ScheduleBlock>
In ScheduleBlock.java, I override onMeasure() to set the size of the block using setMeasuredDimension, and I override onDraw() with the following code:
super.onDraw(canvas);
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
canvas.drawPaint(paint);
String bgColor = "#FF0000";
setBackgroundColor(Color.parseColor(bgColor));
I noticed that red rectangle does appear in the XML file's preview, but not when I try to add the block in ScheduleGridLayout:
FrameLayout blockFrame = (FrameLayout)LayoutInflater.from(getContext()).inflate(R.layout.schedule_block_container, this, false);
testBlock.setElevation(4);
addView(blockFrame);
Not only does the rectangle not appear when I run the app, but I've found that the onDraw() method for ScheduleBlock is not called. What am I doing wrong? How can I make these blocks appear inside my scrollview on top of the gridlines and be interactable with clicks? I'd prefer to be able to do with with custom views if possible, since each block needs to be associated with specific data.

Related

Android Studio: Calling multiple Canvas in ScrollView to display 1 drawing (canvas) after another

I'm writing a code for a school project where one has to load a data file (CSV file, text file, etc) and from the obtained data, the app will pass the data to a custom draw View and the onDraw method will draw/plot a graph based on the data.
My goal is for the app to display 2 graphs, one after the other (stacked). The first set of data is loaded and the 1st graph is drawn. The loaded data is then used for a different calculation in a different method. The custom draw View is then called again with the new data to draw the 2nd graph.
When I run the app, both charts are drawn but because the x and y-axis' of the graph are coded to be drawn at certain fixed pixels, the 2nd graph is drawn over the first one and therefore only the 2nd graph is visible.
Is there any way I can draw the 2 graphs so that it does not overlap and instead appears to be stacked in ScrollView?
My code is shown below but I've gotten rid of calculations that I think aren't very important. Any help and pointers would be very much appreciated!
MainActivity.java:
#Override
protected void onActivityResult(......) {
super.onActivityResult(......);
switch (1) {
case 1:
Graph graph = this.findViewById(R.id.graph1);
graph.setData(data); // the loaded data is passed to Graph View
Graph drawGraph2 = this.findViewById(R.id.graph2);
graph2.setData(this.newCalculate(data));
break;
}
}
Graph.java
public class Graph extends View {
private Paint mPaint = new Paint();
private final int zero = 700; // mark the 0 line of graph at 700 pixels
public void setData(data){
......
}
public Graph(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
plotUnit(canvas); // plot points on graph
axisLabel(canvas); // label axis
axisLine(canvas); // draw axis
xyAxisMarker(canvas); // mark axis
}
private void plotUnit(Canvas canvas) {
......
// Due to data having negative values, the graph is inverted and the 0 starts
// of the graph is defined at 700 pixels (private final int zero)
}
private void axisLabel(Canvas canvas) {
......
}
private void axisLine(Canvas canvas, int inset) {
......
}
private void xyAxisMarker(Canvas canvas) {
......
}
Update
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/loadbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Data File" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph1"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph2"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</LinearLayout>
You cannot have two views' heights match parent height inside of a LinearLayout with vertical orientation. It is not possible because heights of these views must be equal to the parent height but at the same time, they must be ordered one after the other resulting in double of parent's height.
If you imagine parent's height as 10dp then each of the Graph views must be 10dp as well which means parent's height must be 20dp, not 10dp. That is going to cycle forever so the Android does a simple thing: views that are going below the first child view with android:layout_height="match_parent" will have height 0dp or if their height is fixed they will be drawn outside of the layout and will not be visible.
Example
Screenshot from Design tab of layout editor in Android Studio IDE.
Here you can see:
red view as a parent linear layout;
purple view as a first child with height matching it's parent height;
outlined view that is drawn outside of the layout because it is pushed out by the first child with android:layout_height="match_parent";
there is one more view that is crushed to 0 height and thus not visible. You can see it down in the XML code.
XML code of this sample:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#android:color/holo_red_light">
<LinearLayout
android:background="#color/colorPrimary"
android:layout_width="60dp"
android:layout_height="match_parent" <!-- this view's height is a problem -->
android:orientation="vertical"/>
<LinearLayout
android:background="#android:color/holo_green_dark"
android:layout_width="120dp"
android:layout_height="match_parent" <!-- height is not fixed, then it will be 0 -->
android:orientation="vertical"/>
<LinearLayout
android:background="#android:color/holo_green_light"
android:layout_width="120dp"
android:layout_height="40dp" <!-- height is fixed, it is outlined outside of a layout -->
android:orientation="vertical"/>
</LinearLayout>
How to fix the issue?
Set fixed height. As a test try to define a fixed height, e.g. 100dp;
Redesign your layout. Use RelativeLayout or ConstraintLayout to position views relative to each other so that they are always visible no matter what the screen size, ratio, density is.
Example of how to fix
I personally prefer ConstraintLayout as it is very powerful in terms of positioning and adaptation.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/loadbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Open Data File"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph1"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/graph2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/loadbutton" />
<firstapp.drawtwograph.Graph
android:id="#+id/graph2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/graph1" />
</androidx.constraintlayout.widget.ConstraintLayout>
The result is (I used two buttons instead of Graph views):
Hints:
If you want to use ScrollView then setting fixed height or defining height at runtime will be required.
Get rid of private final int zero = 700; // mark the 0 line of graph at 700 pixels. Do not use pixel values directly as it will lead to error-prone UI. It will be the case of "work on my phone, does not work the other". Use view's height as the 0 line.

Android Custom Camera - Crop image inside Rectangle

I have a custom camera app which have a centered rectangle view, as you can see below:
When I take a picture I want to ignore everything outside the rectangle. The view hasn't any connection with the Camera Preview or SurfaceView in my XML view, as follows:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="#+id/cameraview"
android:name="com.kut.camera.KutCameraFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<View android:id="#+id/viewTamanho"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="400px"
android:layout_marginTop="300px"
android:layout_marginStart="70px"
android:layout_marginEnd="70px"
android:background="#drawable/border" />
<RelativeLayout
android:id="#+id/rel_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:alpha="1"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="10dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textViewReferan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Evidência"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/button_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:color/transparent"
android:text="Sair"
android:textColor="#2799CF" />
</RelativeLayout>
<LinearLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/islem_value_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Carregando..." />
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:alpha="0.9"
android:background="#android:color/black"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView_foto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/camera" />
<ImageView
android:id="#+id/imageView_photo"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:padding="5dp"
android:scaleType="fitCenter"
android:src="#drawable/fotoicon" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
Can somebody help me how to crop the image properly? I tried to create a new Bitmap based on my XML but obviously it didn't work, something like:
Camera.PictureCallback jpegCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//.../
Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, 70, 400, imagemOriginal.getWidth() - 70,
imagemOriginal.getHeight() - 400);
//.../
}
I put those initial values for x and y, and tried to subtract (based on XML values from View referring to marginTop, Bottom, etc...) from width and Height but I hadn't success because I don't know how to match View coordinates with the image coordinates taken from Camera. Also, it seems for me Bitmap.createBitmap does limited crop, apparently I can't crop it to a rectangle directly.
To control cropping, you must control the picture size and the rectangle size.
It is very important to a) choose the picture size with same aspect ratio as the preview, and b) make sure that the preview is not distorted on the screen. If you prepare your app for a wide range of devices, both tasks are not trivial. To achieve the latter, you need to control both preview size and the SurfaceView size. I have explained this in more detail elsewhere.
To keep it simple, I suggest to ignore the tablets that may have natural Landscape orientation. On phones, the captured image will be "rotated" 90° even if you set camera orientation to portrait (which only effects preview). Don't expect setRotation() to fix this for you: by the book, it is allowed to simply set the EXIF flag for the captured image.
You set the margins for viewTamanho in px. This may not scale well on variety of screens. I suggest setting the dimensions of this view programmatically, as certain percent of the preview surface. You can use support library to define this in XML, but I am afraid this will not give you enough control.
With all this at hand, let's say that we have preview of 1280×720, picture of 2560×1440, our screen is 1280×800, and the rectangle is in the middle, 616×400 pixels (which is more or less the size scaled from your screenshot).
The actual preview size on screen will be probably 1000x562, padded on the right and left with black margins of 79px. Then the following code will produce the expected captured picture:
public void onPictureTaken(byte[] data, Camera camera) {
//.../
Bitmap imagemOriginal = BitmapFactory.decodeByteArray(data, 0, data.length); // 2560×1440
float scale = 1280/1000F;
int left = (int) scale*(imagemOriginal.getWidth()-400)/2;
int top = (int) scale*(imagemOriginal.getHeight()-616)/2;
int width = (int) scale*400;
int height = (int) scale*616;
Matrix rotationMatrix = new Matrix();
rotationMatrix.postRotate(90);
Bitmap imagemCortada = Bitmap.createBitmap(imagemOriginal, left, top, width, height, rotationMatrix, false);
//.../
}
Here i used this
implementation 'com.otaliastudios:cameraview:2.6.2'
library for getting bitmap image after taking picture.
Here is the code how i achieved this
public void croppingRectangle (Bitmap bitmap, CameraView mCameraView, FrameLayout rectangle) {
int cameraHeight = mCameraView.getHeight();
int cameraWidth = mCameraView.getWidth();
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int leftAndRightMarginsInPixels = Math.round(Math.round(getResources().getDimension(Your_dimens) * 2));`
here i did scaling, after taking picture
int left = (int) Math.round(((double)rectangle.getX()/(double)cameraWidth) * bitmap.getWidth();
int top = (int) Math.round(((double)rectangle.getY()/(double)cameraHeight) * bitmap.getHeight();
int width =
(int) (capturedWidth - Math.round(((double)leftAndRightMarginsInPixels / (double) displayMetrics.widthPixels) * bitmap.getWidth()));
int height = (int) Math.round(((double) rectangle.getHeight() / (double) displayMetrics.heightPixels) * bitmap.getHeight());
Matrix rotationMatrix = new Matrix();
rotationMatrix.postRotate(0);
Bitmap croppedImage = Bitmap.createBitmap(bitmap, left, top, width, height, rotationMatrix, false);
}
P.S : I have achieved 95% accuracy for top & bottom, 70% in getting width of a frame

Why I can't create repeated images and put these into an ImageView of my application?

I am absolutly new in Android development and I have the followind doubt.
I have to draw images one next to each other into a Canvas object.
So let to do an example of what I neeed:
Into the /res/drawable/ folder of my project I have this icon (I have resized it before put it into my project but I think that this is not so important):
So I have to put 3 of these icon one next to each other into a specific ImageView of my activity view (adding some white space between an image and the next one).
So I have done something like this:
1) This is the code of my fragment_screen_slide.xml file that represent the layout where these images have to be placed:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="0dp">
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:layout_height="250dp" />
<TextView android:id="#android:id/text1"
style="#style/pastaTitleTextStyle" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="#style/HeaderTextStyle"
android:text="Difficoltà:" />
<ImageView
android:id="#+id/starContainer"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:layout_height="250dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
In particular these images have to be placed into this ImageView contained in the previous code snippet:
<ImageView
android:id="#+id/starContainer"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:layout_height="250dp" />
Here I have a first doubt because Androi Studio report an error on this line:
android:id="#+id/starContainer"
The reported error is a red underline on the # and when I pass the mouse pointer on it I can read the following error message:
<interface declaration>, <perceable declaration>, AidToken.import or AidTokenTye.package expected, got '#'
It seems strange to me because I am only creatin an id for the ImageView and because I have not problem when Gradle build the project.
Then, into the Java code that actually put the images into the previous ImageView I have done something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("PAGE NUMBER: "+ mPageNumber + 1);
// Create the Canvas where the images are putted:
Canvas difficultyCanvas = creaImgDifficulty();
switch (mPageNumber + 1) {
case 1:
imgSlideView.setImageResource(R.drawable.carbonara);
((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.carbonara));
difficultyCanvas = creaImgDifficulty();
ImageView starContainer = (ImageView) rootView.findViewById(R.id.starContainer);
starContainer.draw(difficultyCanvas);
break;
// OTHER CASES
}
private Canvas creaImgDifficulty() {
Canvas canvas;
Bitmap chefHatOk = BitmapFactory.decodeResource(getResources(), R.star);
Bitmap output = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
int space = 10; // the space between images
for(int i = 0; i < 3; i++) {
canvas.drawBitmap(chefHatOk, i * (chefHatOk.getWidth() + space), 0, null);
}
return canvas;
}
}
So, as you can see in the previous code sippet, when the view is created first I create a new Canvas object (that contains the repeated images) calling the creaImgDifficulty() and then I try to draw this Canvas object into the previous ImageView having id=starContainer.
The creaImgDifficulty() create the Canvas object and draw the bitmap on it 3 times.
I obtain no error when I run the application but the images is not displayed into my ImageView.
Why? What is wrong? What am I missing? How can I try to solve this issue?
XML cannot contain capitals. Switch your ID line to:
android:id="#+id/star_container"
Then change your java file references to match.

adding some picture on the other picture

I need to add some picture (like a flower) to the other picture (main picture) . i want to achieve that after user captures a picture then he can add the picture to that. Is there a library can solve my problem?
just like this picture :
You can use FrameLayout .
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="#+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Or use
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
canvas.drawBitmap(yourBitmap, 0, 0, paint) ; //Draw bitmap
canvas.drawCircle(50, 50, 10, paint); //Draw Circle
imageView.setImageBitmap(bitmap);
OR
You can use this library 'https://github.com/codepath/android_guides/wiki/Basic-Painting-with-Views'

How to write Text on ImageView in android coding?

Hi I've been trying to write Numbers on Imageview. Images for N number of questions. If the user entered answer is correct, then it should be displayed with question number with tick mark image else question number with wrong mark image. I need to write the question number on the image. My code is here:
LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_view_report);
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
ImageView[] imgview=new ImageView[questions.length];
for(int i=0;i<no_of_questions;i++)
{
if(userEnteredAnswers[i]==correct_answer[i]){
Bitmap bm=BitmapFactory.decodeResource(getResources(),R.drawable.correct);
Canvas canvas = new Canvas(bm);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(10);
canvas.drawText(i, 5, 5, paint);
imgview[i]=new ImageView(this);
imgview[i].setImageDrawable(new BitmapDrawable(bm));
l_layout.addView(imgview[i]);
}
else {
Bitmap bm=BitmapFactory.decodeResource(getResources(),R.drawable.wrong);
Canvas canvas = new Canvas(bm);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(10);
canvas.drawText(i, 5, 5, paint);
imgview[i]=new ImageView(this);
imgview[i].setImageDrawable(new BitmapDrawable(bm));
l_layout.addView(imgview[i]);
}
}
I get this warning:
The constructor BitmapDrawable(Bitmap) is deprecated
Image doesn't showing at run time.
What am I doing wrong?
I believe the easiest workaround without overriding anything would be to have a TextView and set its background with a drawable resource.
For instance:
TextView t = (TextView)findViewById(R.id.my_text_view);
// setting gravity to "center"
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.my_drawable);
t.setText("FOO");
From the Android documentation :
BitmapDrawable(Bitmap bitmap)
This constructor was deprecated in API level 4. Use BitmapDrawable(Resources, Bitmap) to ensure that the drawable has correctly set its target density.
You can also create your own view (see Android: Creating Custom Views tutorial for an example) and put you image and the text in this view.
1). Make your own layout Say Image_TextView.xml like this :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="150dp"
android:layout_height="150dp"
android:gravity="center" >
<ImageView
android:id="#+id/imgview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:cropToPadding="true"
android:scaleType="center"
android:src="#drawable/box" />
<RelativeLayout
android:layout_width="150dp"
android:layout_height="35dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="0dp"
android:background="#80666666" >
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Hello"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
This will make Image with Text over it.
2). Then use layout inflator to inflate this view in your parent view.
Note : Using layout inflator you can add other view to your parent view.
its not possible to write text on imageview, but you can extend it to do so. Alternatively,
you can add an element overlapping the ImageView in the layout, and make it visible only when your condition becomes true.
or, you can use textView to display image, as a background or as a drawable to left/right..
Ps: however, the option 1 is easier to implement, but it will have additional rendering. so consider the other option first.

Categories

Resources