You are on page 1of 75

LAB MANUAL -ADDITIONAL PROGRAM

1
1.Objective: Design a gaming application

Preparing Images and sounds


You need a few images

 chibi1.png

 chibi2.png

 explosion.png

The Audio file of the explosion.

 explosion.wav

Background sound:

 background.mp3

Copy these images to the drawable folder of project. Create raw folder,
and copy explosion.wav & background.mp3 to this folder.
4- Setting fullscreen (Version:1)
With games, you need to set the background image and an important thing is that you need to
set FullScreen mode.

Your MainActivity class must extends from the Activity class .


MainActivity.java (Version: 1)
?
1 package org.o7planning.androidgame2d;

3 import

4 android.app.Activity;

import android.os.Bundle;
5
import android.view.Window;
6
import android.view.WindowManager;
7

8
public class MainActivity extends Activity {
9

10
@Override
11
protected void onCreate(Bundle savedInstanceState)
12
{ super.onCreate(savedInstanceState);
13

14
// Set fullscreen
15
this.getWindow().setFlags(WindowManager.LayoutPar
16 ams.FLAG_FULLSCREEN,

17 WindowManager.LayoutParams.FLAG_FULLSCREE
N);
18

19
// Set No Title
20
this.requestWindowFeature(Window.FEATURE_NO_TITLE
21 );

22

}
23
}

Running apps:

Next, set screen is Landscape. You need to set in AndroidManifest.xml.


?
1 android:screenOrientation="landscape"

Rerun apps:

Note: On Windows you can also change the direction of the simulater by Ctrl + F11.

5- Show character in the game (Version:2)


Next you need to write code to show the game character on the screen and move it from left to
right in a certain speed.
With a character in the game you only have one image file, but the image are divided into several
regions described the different actions of the character.

Using the code you can draw a picture to the Canvas of the game, at the x, y coordinates. Use a
loop to continuously draw on the Canvas, you can create the movement of the character.
When programming a game, you also need to pay attention to the movement direction of
the characters in the game, the speed of the character.

Create a Gameobject class, objects of the game is extended from this class.
GameObject.java (Version: Release)
?

1 package org.o7planning.androidgame2d;

3
import android.graphics.Bitmap;
4

5
public abstract class GameObject {
6

7
protected Bitmap image;
8

9
protected final int
10
rowCount; protected final
11
int colCount;
12

13
protected final int
14
WIDTH; protected final
15
int HEIGHT;
16

17 protected final int width;


18

19

20 protected final int


21 height; protected int x;

protected int y;
22 public GameObject(Bitmap image, int rowCount,
int colCount, int x, int y) {
23

24
this.image = image;
25
this.rowCount= rowCount;
26
this.colCount= colCount;
27

28
this.x= x;
29
this.y= y;
30

31 this.WIDTH = image.getWidth();
32 this.HEIGHT = image.getHeight();
33

34 this.width = this.WIDTH/ colCount;


35 this.height= this.HEIGHT/ rowCount;

36 }

37

38

39 protected Bitmap createSubImageAt(int row, int col){

40 // createBitmap(bitmap, x, y, width, height).

41 Bitmap subImage = Bitmap.createBitmap(image, col*


width, row* height ,width,height);
42
return subImage;
43
}
44

45 public int getX() {

46 return this.x;

47 }

48

49 public int getY() {

return this.y;
50
}
51

52

53
public int getHeight()
54
{ return height;
55
}
56

57
public int getWidth()
58
{ return width;
59
}
60

61
}
62

63

ChibiCharacter Class simulates a character in the game.


ChibiCharacter.java (Version: 2)
?
1 package org.o7planning.androidgame2d;

3
import
4
android.graphics.Bitmap;
5
import
6
android.graphics.Canvas;
7

8
public class ChibiCharacter extends GameObject {
9

10
private static final int ROW_TOP_TO_BOTTOM =
11
0; private static final int
12
ROW_RIGHT_TO_LEFT = 1; private static final
13
int ROW_LEFT_TO_RIGHT = 2; private static
14
final int ROW_BOTTOM_TO_TOP = 3;
15

16
// Row index of Image are being used.
17 private int rowUsing =
18 ROW_LEFT_TO_RIGHT;
19

20 private int colUsing;

21

22 private Bitmap[]

leftToRights; private
Bitmap[] rightToLefts;

private Bitmap[]

topToBottoms; private

Bitmap[] bottomToTops;
23 // Velocity of game character (pixel/millisecond)

24 public static final float VELOCITY = 0.1f;

25

26 private int movingVectorX =

27 10; private int movingVectorY

= 5;
28

29
private long lastDrawNanoTime =-1;
30

31
private GameSurface gameSurface;
32

33
public ChibiCharacter(GameSurface gameSurface, Bitmap
34 image, int x, int y) {

35 super(image, 4, 3, x, y);
36

37 this.gameSurface= gameSurface;

38

39 this.topToBottoms = new Bitmap[colCount]; //

40 3 this.rightToLefts = new

41 Bitmap[colCount]; // 3 this.leftToRights =

42 new Bitmap[colCount]; // 3 this.bottomToTops

43 = new Bitmap[colCount]; // 3

44
for(int col = 0; col< this.colCount; col++ )

{ this.topToBottoms[col] =
this.createSubImageAt(ROW_TOP_TO_BOTTOM, col);
45 this.rightToLefts[col] =
this.createSubImageAt(ROW_RIGHT_TO_LEFT,
46 col);

47 this.leftToRights[col] =
this.createSubImageAt(ROW_LEFT_TO_RIGHT, col);
48
this.bottomToTops[col] =
49 this.createSubImageAt(ROW_BOTTOM_TO_TOP,

50 col);
}
51
}
52

53
public Bitmap[] getMoveBitmaps() {
54
switch (rowUsing) {
55
case ROW_BOTTOM_TO_TOP:
56
return
57
this.bottomToTops;
58
case ROW_LEFT_TO_RIGHT:
59
return
60
this.leftToRights;
61
case ROW_RIGHT_TO_LEFT:
62
return
63 this.rightToLefts;
64 case ROW_TOP_TO_BOTTOM:
65 return
66 this.topToBottoms;

default:
return
null;
}

public Bitmap getCurrentMoveBitmap() {


67 Bitmap[] bitmaps = this.getMoveBitmaps();

68 return bitmaps[this.colUsing];

69 }

70

71

72 public void update() {

this.colUsing++;
73
if(colUsing >= this.colCount) {
74
this.colUsing =0;
75
}
76
// Current time in nanoseconds
77
long now = System.nanoTime();
78

79
// Never once did draw.
80
if(lastDrawNanoTime==-1)
81
{
82
lastDrawNanoTime= now;
83
}
84 // Change nanoseconds to milliseconds (1
85 nanosecond = 1000000 milliseconds).
int deltaTime = (int) ((now - lastDrawNanoTime)/
86
1000000 );
87

88
// Distance moves

float distance = VELOCITY * deltaTime;


89

90 double movingVectorLength =
Math.sqrt(movingVectorX* movingVectorX +
91 movingVectorY*movingVectorY);

92

93 // Calculate the new position of the game


character.
94
this.x = x + (int)(distance* movingVectorX
95 / movingVectorLength);

96 this.y = y + (int)(distance* movingVectorY


/ movingVectorLength);
97

98
// When the game's character touches the edge of
99
the screen, then change direction
100

101
if(this.x < 0 ) {
102 this.x = 0;
103 this.movingVectorX = - this.movingVectorX;
104 } else if(this.x > this.gameSurface.getWidth()
- width) {
105
this.x= this.gameSurface.getWidth()-width;
106
this.movingVectorX = - this.movingVectorX;
107
}
108

109
if(this.y < 0 ) {
110
this.y = 0;
111 this.movingVectorY = - this.movingVectorY;

112 } else if(this.y >


this.gameSurface.getHeight()- height) {
113
this.y= this.gameSurface.getHeight()- height;
114
this.movingVectorY = - this.movingVectorY ;
115
}
116

117
// rowUsing
118
if( movingVectorX > 0 ) {
119 if(movingVectorY > 0
120 &&
Math.abs(movingVectorX) < Math.abs(movingVectorY)) {
121
this.rowUsing = ROW_TOP_TO_BOTTOM;
122
}else if(movingVectorY < 0 &&
123
Math.abs(movingVectorX) < Math.abs(movingVectorY)) {
124 this.rowUsing = ROW_BOTTOM_TO_TOP;
125 }else {
126 this.rowUsing = ROW_LEFT_TO_RIGHT;
127 }
128 } else {

129 if(movingVectorY > 0 &&


Math.abs(movingVectorX) < Math.abs(movingVectorY)) {
130
this.rowUsing = ROW_TOP_TO_BOTTOM;
131
}else if(movingVectorY < 0 &&
132 Math.abs(movingVectorX) < Math.abs(movingVectorY)) {

this.rowUsing = ROW_BOTTOM_TO_TOP;
133 }else {

134 this.rowUsing = ROW_RIGHT_TO_LEFT;

135 }

136 }

137 }

138

139 public void draw(Canvas canvas) {

Bitmap bitmap = this.getCurrentMoveBitmap();


140
canvas.drawBitmap(bitmap,x, y, null);
141
// Last draw time.
142
this.lastDrawNanoTime= System.nanoTime();
143
}
144

145
public void setMovingVector(int movingVectorX,
146 int movingVectorY) {

147 this.movingVectorX= movingVectorX;

this.movingVectorY = movingVectorY;

1 Game Thread is a thread that controls the update of the game interface.
package org.o7planning.androidgame2d;
GameThread.java (Version: Release)
2 ?
3

4 import android.graphics.Canvas;

5 import

6 android.view.SurfaceHolder;

8 public class GameThread extends Thread {

9
private boolean running;
10
private GameSurface gameSurface;
11
private SurfaceHolder
12
surfaceHolder;
13

14
public GameThread(GameSurface
15 gameSurface, SurfaceHolder surfaceHolder)
{
16
this.gameSurface= gameSurface;
17
this.surfaceHolder= surfaceHolder;
18
}
19

20
@Override
21
public void run() {
22
long startTime = System.nanoTime();
23

24
while(running)

{ Canvas canvas=
null; try {

// Get Canvas from Holder and lock it.


25 canvas =
this.surfaceHolder.lockCanvas();
26

27
// Synchronized
28
synchronized (canvas) {
29
this.gameSurface.update();
30
this.gameSurface.draw(canvas);
31
}
32
}catch(Exception e) {
33 // Do nothing.
34 } finally {
35 if(canvas!= null) {
36 // Unlock Canvas.

37 this.surfaceHolder.unlockCanvasAndPo
st(canvas);
38
}
39
}
40
long now = System.nanoTime() ;
41
// Interval to redraw game
42
// (Change nanoseconds to milliseconds)
43
long waitTime = (now -
44
startTime)/1000000; if(waitTime < 10) {
45
waitTime= 10; // Millisecond.
46 }
47 System.out.print(" Wait Time="+ waitTime);

48

49 try {

50 // Sleep.

51 this.sleep(waitTime);

52 } catch(InterruptedException e) {

53
}
54
startTime = System.nanoTime();
55
System.out.print(".");
56
}
57
}
58

59
public void setRunning(boolean running){
60
this.running= running;
61
}
62
}
63

64

1 package
the entire surface org.o7planning.androidgame2d;
of the game. This class extends from SurfaceView, SurfaceView contains a Canvas object, the objects in the

GameSurface.java (Version: 2)
?
2

4 import

5 android.content.Context;

6 import

7 android.graphics.Bitmap;

import
8
android.graphics.BitmapFactory;
9
import android.graphics.Canvas;
10
import android.view.MotionEvent;
11
import android.view.SurfaceHolder;
12
import android.view.SurfaceView;
13

14
public class GameSurface extends SurfaceView
15 implements SurfaceHolder.Callback {

16

17

18 private GameThread gameThread;

19

20 private ChibiCharacter chibi1;

21

22 public GameSurface(Context context) {

23 super(context);

// Make Game Surface focusable so it can handle


events. .

this.setFocusable(true);
24

25 // Sét callback.

26 this.getHolder().addCallback(this);

27 }

28

29 public void update() {

this.chibi1.update();
30
}
31

32

33

34
@Override
35
public void draw(Canvas canvas) {
36
super.draw(canvas);
37

38
this.chibi1.draw(canvas);
39
}
40

41
// Implements method of SurfaceHolder.Callback
42
@Override
43
public void surfaceCreated(SurfaceHolder holder) {
44
Bitmap chibiBitmap1 =
45 BitmapFactory.decodeResource(this.getResources(),R.drawab
le.chibi1);
46 this.chibi1 = new
ChibiCharacter(this,chibiBitmap1,100,50);
47

48
this.gameThread = new GameThread(this,holder);
49
this.gameThread.setRunning(true);
50
this.gameThread.start();
51
}
52

53
// Implements method of SurfaceHolder.Callback
54 @Override
55 public void surfaceChanged(SurfaceHolder holder,
56 int format, int width, int height) {

57
}
58

59
// Implements method of SurfaceHolder.Callback
60
@Override
61
public void surfaceDestroyed(SurfaceHolder holder)
62
{ boolean retry= true;
63
while(retry) {
64
try {
65
this.gameThread.setRunning(false);
66

67
// Parent thread must wait until the end
68 of GameThread.

69 this.gameThread.join();

70 }catch(InterruptedException e) {

71 e.printStackTrace();

72 }
retry= true;
73
}
74
}
75

76
}

MainActivity.java (Version: Release)


?
package org.o7planning.androidgame2d;
1

2
import
3
android.app.Activity;
4
import android.os.Bundle;
5
import android.view.Window;
6
import android.view.WindowManager;
7

8
public class MainActivity extends Activity {
9

10
@Override
11
protected void onCreate(Bundle savedInstanceState)

{ super.onCreate(savedInstanceState);
12

13 // Set fullscreen

14 this.getWindow().setFlags(WindowManager.LayoutPa
rams.FLAG_FULLSCREEN,
15
WindowManager.LayoutParams.FLAG_FULLSCRE
16 EN);

17

18 // Set No Title

19 this.requestWindowFeature(Window.FEATURE_NO_TITL
E);
20

21
this.setContentView(new GameSurface(this));
22
}
23
}
24

25

OK, 2nd version is completed, you can run the game.


Sr. Experiment No. 9:
No. Design a gaming application.
Viva Questions
1 What is the basic structure for developing a game?
2 What is “Pixel Art”?
3 What do you mean by “Lag” ?
4 What are the Android tools used for developing games?
5 In Android, how you can use load texture method to load the image?
6 What is a game loop?
7 What are the common errors done by programmer while programming?
8 What are the gaming engines you can use for developing games?
9 Describe Lifecycle of an Activity.
10 Why would you do the setContentView() in onCreate() of Activity class?
2.Objective: - Create an application to handle images according to size

Designing layout for the Android Application:

 Click on app -> res -> layout -> activity_main.xml.

 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.

Code for Activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
1
android:id="@+id/flavor"
2
xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
xmlns:tools="http://schemas.android.com/tools"
5
android:layout_width="match_parent"
6
android:layout_height="match_parent"
7
android:background="@drawable/flavor"
8
tools:context=".MainActivity">
9

10
<ImageView
11
android:id="@+id/add"
12
android:layout_width="125dp"
13
android:layout_height="125dp"
14
android:src="@drawable/cropit"
15
android:layout_centerInParent="true"/> //Add
16

17
<TextView
18
android:id="@+id/text"
19
android:layout_below="@id/add"
20
android:layout_centerHorizontal="true"
21
android:layout_marginTop="30dp"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:textSize="30dp"

android:textStyle="bold"

android:textColor="#FFFFFF"

android:text="Tap to Cropfit"/> //Tap to

cropfit

<RelativeLayout

android:id="@+id/story"

android:layout_width="450dp"

android:layout_height="800dp"

android:gravity="center"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true">

<com.jgabrielfreitas.core.BlurImageView

android:id="@+id/storyBlur"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:adjustViewBounds="true"

android:scaleType="centerCrop"/>
<LinearLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/shadow

" android:gravity="center"

android:padding="3dp">

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#FFFFFF"

android:padding="3dp">

<ImageView

android:id="@+id/showStory"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:adjustViewBounds="true"/>

</LinearLayout>

</LinearLayout>

<LinearLayout
android:id="@+id/copyright"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_alignParentBottom="true

" android:layout_marginEnd="5dp"

android:layout_marginBottom="3dp"

android:orientation="horizontal">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content

" android:alpha="0.5"

android:text="CR"

android:textColor="#FFFFFF"

android:textSize="14dp"

android:textStyle="bold" />

<ImageView

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:alpha="0.5"

android:src="@drawable/refresh" />
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:alpha="0.5"

android:text="PFIT"

android:textColor="#FFFFFF"

android:textSize="14dp"

android:textStyle="bold" />

</LinearLayout> //Copyright

</RelativeLayout> //Story

<RelativeLayout

android:id="@+id/post"

android:layout_width="320dp"

android:layout_height="320dp

" android:gravity="center"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true">

<com.jgabrielfreitas.core.BlurImageView

android:id="@+id/postBlur"

android:layout_width="match_parent"
android:layout_height="match_parent"

android:gravity="center"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:adjustViewBounds="true"

android:scaleType="centerCrop"/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:background="@drawable/shadow

" android:gravity="center"

android:padding="3dp">

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#FFFFFF"

android:padding="3dp">

<ImageView

android:id="@+id/showPost"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:adjustViewBounds="true"/>

</LinearLayout>

</LinearLayout>

</RelativeLayout> //Post

<LinearLayout

android:visibility="gone"

android:id="@+id/button

"

android:layout_alignParentBottom="true

" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_marginBottom="30dp">

<TextView

android:id="@+id/one"

android:layout_width="100dp

"

android:layout_height="match_parent"

android:text="Portrait"

android:textColor="#FFFFFF"

android:textStyle="bold"
android:gravity="center"
android:layout_marginRight="15dp"

android:background="@drawable/circle"

android:padding="7dp"

android:textSize="18dp"/>

<TextView

android:id="@+id/zero"

android:layout_width="100dp

"

android:layout_height="match_parent"

android:text="Square"

android:textColor="#FFFF00"

android:textStyle="bold"

android:gravity="center"

android:textSize="20dp"

android:layout_marginRight="15dp"

android:background="@drawable/circle"

android:padding="7dp"/>

</LinearLayout> //Action

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"
android:background="@drawable/circle"

android:padding="7dp"

android:layout_marginTop="30dp">

<ImageView

android:id="@+id/refresh"

android:layout_width="40dp"

android:layout_height="40dp"

android:src="@drawable/refresh"/>

<ImageView

android:id="@+id/save"

android:layout_width="40dp"

android:layout_height="40dp"

android:src="@drawable/save

"

android:layout_marginLeft="20dp"/>

<ImageView

android:id="@+id/share"

android:layout_width="40dp"

android:layout_height="40dp"

android:src="@drawable/share

"

android:layout_marginLeft="20dp"/>

<ImageView

android:id="@+id/nacy"
android:layout_width="40dp

"
android:layout_height="40dp"

android:src="@drawable/nacy_dddd

"

android:layout_marginLeft="20dp"/>

</LinearLayout> //Menu

<LinearLayout

android:paddingLeft="24dp"

android:id="@+id/saved"

android:layout_width="230dp"

android:layout_height="55dp"

android:layout_centerHorizontal="true"

android:gravity="center"

android:orientation="vertical"

android:layout_marginTop="30dp">

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="CROPFIT SAVED"

android:gravity="center"

android:textSize="19dp"

android:textStyle="bold"

android:textColor="#FFFF00"/>

<TextView

android:layout_width="match_parent"
android:layout_height="wrap_content"

android:text="Check Phone Storage"

android:textSize="15dp"

android:gravity="center"

android:layout_marginTop="-7dp"

android:textColor="@color/colorAccent"/

>

</LinearLayout> //Saved

</RelativeLayout>

Code for AndroidManifest.xml:


1 <?xml version="1.0" encoding="utf-8"?>

2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

3 package="com.nacy.cropfit">

5 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
/>
6
<uses-permission
7 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
8

9 <application
10 android:allowBackup="true"
11 android:icon="@mipmap/ic_launcher"
12 android:label="@string/app_name"
13 android:roundIcon="@mipmap/ic_launcher_round"
14 android:supportsRtl="true"

15 android:theme="@style/AppTheme">

16 <activity android:name=".MainActivity">

17 <intent-filter>

18 <action android:name="android.intent.action.MAIN" />

19

20 <category android:name="android.intent.category.LAUNCHER" />

21 </intent-filter>

</activity>

</application>

</manifest>

 So now the Permissions are added in the

Manifest. Java Coding for the Android Application:

 Click on app -> java -> com.example.exno9 -> MainActivity.

 Then delete the code which is there and type the code as given below.

Code for MainActivity.java:

1 package com.nacy.cropfit;

3 import android.Manifest;

4 import android.content.Intent;

5 import android.content.pm.ActivityInfo;

6 import android.content.pm.PackageManager;

7 import android.database.Cursor;
8 import android.graphics.Bitmap;

9 import

10 android.graphics.BitmapFactory;

11 import android.graphics.Canvas;

12 import android.graphics.Color;

13 import android.graphics.drawable.AnimationDrawable;

14 import android.net.Uri;

15 import android.os.Environment;

16 import android.os.Handler;

17 import android.provider.MediaStore;

18 import android.support.v4.app.ActivityCompat;

19 import android.support.v4.content.ContextCompat;

20 import android.support.v7.app.AppCompatActivity;

21 import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.WindowManager;

import android.view.animation.Animation;

import android.view.animation.AnimationUtils;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.RelativeLayout;

import android.widget.TextView;
import android.widget.Toast;
import com.jgabrielfreitas.core.BlurImageView;

import java.io.File;

import

java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

RelativeLayout flavor, story, post;

LinearLayout button, copyright,

saved;

Animation roatation;

BlurImageView postBlur,

storyBlur;

private static int RESULT_LOAD_IMAGE = 1;

String picturePath;

Bitmap

myBitmap; static

File f1;
TextView text, one, zero;

ImageView add, showStory, showPost, save, refresh, nacy, share;


@Override

protected void onCreate(Bundle savedInstanceState)

{ super.onCreate(savedInstanceState);

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.activity_main)

; text = findViewById(R.id.text);

showStory =

findViewById(R.id.showStory); showPost =

findViewById(R.id.showPost); storyBlur =

findViewById(R.id.storyBlur); postBlur =

findViewById(R.id.postBlur); one =

findViewById(R.id.one);

zero = findViewById(R.id.zero);

//Initial Action

story = findViewById(R.id.story);

story.setVisibility(View.INVISIBLE);

post = findViewById(R.id.post);

post.setVisibility(View.INVISIBLE);

button = findViewById(R.id.button);

button.setVisibility(View.INVISIBLE);
saved = findViewById(R.id.saved);

saved.setVisibility(View.INVISIBLE);

copyright =

findViewById(R.id.copyright);

copyright.setVisibility(View.INVISIBLE);

share = findViewById(R.id.share);

share.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Intent shareIntent = new Intent(Intent.ACTION_SEND);

shareIntent.setType("text/plain");

shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Cropfit

App");

shareIntent.putExtra(Intent.EXTRA_TEXT, "No more adjust your post and


story to fit in any frame, Just crop it well with Cropfit App. Download The Cropfit App,
Now available on Play Store.");

startActivity(Intent.createChooser(shareIntent, "Share Using : "));

});

save = findViewById(R.id.save);

save.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Add An Image To Save",
Toast.LENGTH_SHORT).show();

roatation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.roatation);

autoAnime();

});

refresh = findViewById(R.id.refresh);

refresh.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v)

{ Intent intent = getIntent();

finish();

startActivity(intent);

overridePendingTransition(R.anim.fadein, R.anim.fadeout);

saved.setVisibility(View.INVISIBLE);

save.setVisibility(View.VISIBLE);

share.setVisibility(View.VISIBLE);

nacy.setVisibility(View.VISIBLE);

});

nacy = findViewById(R.id.nacy);

nacy.setOnClickListener(new View.OnClickListener() {
@Override

public void onClick(View v) {

Intent about = new Intent(Intent.ACTION_VIEW,


Uri.parse("https://nacyapps.blogspot.com/2019/07/cropfit-no-more-adjust-your-
post- and.html"));

startActivity(about);

});

//Animation

flavor = findViewById(R.id.flavor);

AnimationDrawable animationDrawableK =
(AnimationDrawable) flavor.getBackground();

animationDrawableK.setEnterFadeDuration(2000)

animationDrawableK.setExitFadeDuration(4000);

animationDrawableK.start();

roatation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.roatation);

autoAnime();

//Image Adding

add.setOnClickListener(new View.OnClickListener() {
@Override

public void onClick(View v) {

// Here, thisActivity is the current activity

if

(ContextCompat.checkSelfPermission(MainActivity.t

his, Manifest.permission.READ_CONTACTS)

!= PackageManager.PERMISSION_GRANTED) {

// Permission is not granted

// Should we show an explanation?

if

(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.t

his, Manifest.permission.READ_CONTACTS)) {

// Show an explanation to the user *asynchronously* -- don't block

// this thread waiting for the user's response! After the user

// sees the explanation, try again to request thepermission.

} else {

// No explanation needed; request the permission

ActivityCompat.requestPermissions(MainActivity.this
1);
,

new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},

} else {
// Permission has already been granted

}
Intent i = new

Intent( Intent.ACTION_PICK,

android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(i, RESULT_LOAD_IMAGE);

});

private void autoAnime() {

add = findViewById(R.id.add);

add.startAnimation(roatation);

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

{ super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK


&& null != data) {

Uri selectedImage = data.getData();

String[] filePathColumn = {MediaStore.Images.Media.DATA};


Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null, null);

cursor.moveToFirst();

int columnIndex =

cursor.getColumnIndex(filePathColumn[0]); picturePath =

cursor.getString(columnIndex);

cursor.close();

add.setVisibility(View.INVISIBLE)

text.setVisibility(View.INVISIBLE);

button.setVisibility(View.VISIBLE);

post.setVisibility(View.VISIBLE);

showPost.setImageBitmap(BitmapFactory.decodeFile(picturePath));

postBlur.setImageBitmap(BitmapFactory.decodeFile(picturePath));

postBlur.setBlur(2);

save.setOnClickListener(new View.OnClickListener()

{ @Override

public void onClick(View v) {

myBitmap = captureScreen(post);

//myBitmap =
captureScreen(viewmainroot); try {
if (myBitmap != null)

{ saveImage(myBitma

p);

} catch (Exception e)

{ e.printStackTrace();

});

one.setOnClickListener(new View.OnClickListener()

{ @Override

public void onClick(View v)

{ story.setVisibility(View.VISIBLE);

post.setVisibility(View.INVISIBLE);

showStory.setImageBitmap(BitmapFactory.decodeFile(picturePath));

storyBlur.setImageBitmap(BitmapFactory.decodeFile(picturePath));

storyBlur.setBlur(2);

one.setTextColor(Color.parseColor("#FFFF00"));

zero.setTextColor(Color.parseColor("#FFFFFF"));

saved.setVisibility(View.INVISIBLE);

save.setVisibility(View.VISIBLE);
share.setVisibility(View.VISIBLE)

nacy.setVisibility(View.VISIBLE);

save.setOnClickListener(new View.OnClickListener()

{ @Override

public void onClick(View v) {

copyright.setVisibility(View.VISIBLE);

myBitmap = captureScreen(story);

//myBitmap = captureScreen(viewmainroot);

try {

if (myBitmap != null)

{ saveImage(myBitma

p);

copyright.setVisibility(View.INVISIBLE);

} catch (Exception e)

{ e.printStackTrace(

);

});
}
});
}
zero.setOnClickListener(new View.OnClickListener()

{ @Override

public void onClick(View v)

{ post.setVisibility(View.VISIBLE);

story.setVisibility(View.INVISIBLE);

showPost.setImageBitmap(BitmapFactory.decodeFile(picturePath));

postBlur.setImageBitmap(BitmapFactory.decodeFile(picturePath));

postBlur.setBlur(2);

one.setTextColor(Color.parseColor("#FFFFFF"));

zero.setTextColor(Color.parseColor("#FFFF00"));

saved.setVisibility(View.INVISIBLE);

save.setVisibility(View.VISIBLE);

share.setVisibility(View.VISIBLE);

nacy.setVisibility(View.VISIBLE);

save.setOnClickListener(new View.OnClickListener()

{ @Override

public void onClick(View v) {

myBitmap = captureScreen(post);

//myBitmap = captureScreen(viewmainroot);
try {

if (myBitmap != null)

{ saveImage(myBitma

p);

} catch (Exception e)

{ e.printStackTrace(

);

});

});

public static Bitmap captureScreen(View v)

{ Bitmap screenshot = null;

try {

if (v != null) {

screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

Canvas canvas = new

Canvas(screenshot); v.draw(canvas);
}
} catch (Exception e) {

Log.d("ScreenShotActivity", "Failed to capture screenshot because:"


+ e.getMessage());

return screenshot;

public void saveImage(Bitmap bitmap) {

String state =

Environment.getExternalStorageState(); File

imagePath = null;

final String dirPath = Environment.getExternalStorageDirectory() +

"/Cropfit"; File dir = new File(dirPath);

if (!dir.exists())

{ dir.mkdirs();

else {

//Toast.makeText(Handit.this, "all ready created", Toast.LENGTH_SHORT).show();

if (Environment.MEDIA_MOUNTED.equals(state))

{ Random rand = new Random();

int n =

rand.nextInt(1000); n +=
1;
imagePath = new File(dirPath, "Cropfit"+n+".png");

if (imagePath.exists())

{n=

rand.nextInt(1000); n

+= 1;

f1 = new File(dirPath,"Cropfit"+n+".png");

saved.setVisibility(View.VISIBLE);

save.setVisibility(View.INVISIBLE);

share.setVisibility(View.INVISIBLE);

nacy.setVisibility(View.INVISIBLE);

//File imagePath = new File(Environment.getExternalStorageDirectory() +


"/screenshot.png");

FileOutputStream

fos; try {

fos = new FileOutputStream(imagePath);

bitmap.compress(Bitmap.CompressFormat.PNG, 80,

fos); fos.flush();

fos.close();

} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);

} catch (IOException e)

{ Log.e("GREC", e.getMessage(), e);

} catch (Exception ex)

{ ex.printStackTrace();

@Override

public void onRequestPermissionsResult(int requestCode, String[] permissions,


int[] grantResults) {

switch (requestCode)

{ case 1 : {

// If request is cancelled, the result arrays are

empty. if (grantResults.length > 0

&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the

// contacts-related task you need to do.

} else {

// permission denied, boo! Disable the

// functionality that depends on this permission.

return;

}
// other 'case' lines to check for other

// permissions this app might request

Sr. Experiment No. 10:


No. Create an application to handle images and videos according to size.
Viva Questions
1 What is nine-patch images tool in android?
2 What is a bitmap image?
3 Explain Bitmap Class
4 What is Orientation?
5 How to show image using ImageView in Android?
6 What is the difference between a regular .png and a nine-patch image?
7 What is Dalvik Virtual Machine?
8 How Android app runs on Android mobile?
9 What is Toast in Android?
10 What are Loaders in Android?

You might also like