I have a massive question to ask as I am really stuck on this and it would be create to get ads on my free application, ok first off I have been following this book
Beginning Android games 2011
http://www.apress.com/9781430230427
Now this book implements a very nice and simple game framework which I use (a simpler version can be found here
http://www.kilobolt.com/day-5-the-android-game-framework-part-i.html
Now this framework doesn't use any type of XML file what so ever, it uses a framebuffer to draw things onto the screen. now when the application is first started, this is the first method called which is in the AndroidGame.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int frameBufferWidth = isPortrait ? 480: 800;
int frameBufferHeight = isPortrait ? 800: 480;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
setContentView(renderView);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
}
Where in here could i try and implement the admob banner? Also this is what a screen class looks like
public LogoScreen(Game game)
{
super(game);
}
#Override
public void update(float deltaTime)
{
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i ++)
{
try
{
TouchEvent event = (TouchEvent) touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_DOWN)
{
game.setScreen(new MainMenuScreen(game));
}
}
catch(IndexOutOfBoundsException io)
{
}
}
}
#Override
public void paint(float deltaTime)
{
Graphics g = game.getGraphics();
g.drawImage(Assets.logoScreen, 0, 0);
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public void backButton()
{
android.os.Process.killProcess(android.os.Process.myPid());
}
If I wanted to display an admob advert in the logoScreen what could i do that would work? I am really confused on how I can implement admob into my application, if any one can shine some light on this or help me that would be great :)
Thank you
Canvas
---Update---
Here is the code for the FastRenderView
package com.CC.framework.implementation;
//Imports
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class AndroidFastRenderView extends SurfaceView implements Runnable
{
//Variables
AndroidGame game;
Bitmap framebuffer;
Thread renderThread = null;
SurfaceHolder holder;
volatile boolean running = false;
public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer)
{
super(game);
this.game = game;
this.framebuffer = framebuffer;
this.holder = getHolder();
}
public void resume()
{
running = true;
renderThread = new Thread(this);
renderThread.start();
}
public void run()
{
Rect dstRect = new Rect();
long startTime = System.nanoTime();
while(running)
{
if(!holder.getSurface().isValid())
{
continue;
}
float deltaTime = (System.nanoTime() - startTime) / 10000000.000f;
startTime = System.nanoTime();
if (deltaTime > 3.15)
{
deltaTime = (float) 3.15;
}
game.getCurrentScreen().update(deltaTime);
game.getCurrentScreen().paint(deltaTime);
Canvas canvas = holder.lockCanvas();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(framebuffer, null, dstRect, null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause()
{
running = false;
while(true)
{
try
{
renderThread.join();
break;
}
catch (InterruptedException e)
{
// retry
}
}
}
}
Create a layout container and put the AdView and the renderView in it:
RelativeLayout layout = new RelativeLayout(this);
AdView adView = new AdView(this, AdSize.BANNER, "a151bf25136cf46");
layout.addView(renderView);
layout.addView(adView);
setContentView(layout);
adView.loadAd(new AdRequest());
EDIT 2020:
Code above is 7 years old and the Google Mobile Ads SDK has changed a lot since then. Here's a minimal code example against the current latest SDK version.
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.loadAd(new AdRequest.Builder().build());
setContentView(layout);
I tried it last night and got cool result, see my code in Oncreate() of your Activity:
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setGravity(Gravity.BOTTOM|Gravity.CENTER);
// Create a banner ad
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
// Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
/*For Test On Real Device*/
AdRequest adRequest= new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setId(R.id.linear);
linearLayout.setGravity(Gravity.BOTTOM | Gravity.CENTER);
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 9f);
layoutParams1.gravity = Gravity.TOP;
view.setLayoutParams(layoutParams1);
int heightPixels = AdSize.FULL_BANNER.getHeightInPixels(this);
LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, heightPixels, 0f);
layoutParams2.gravity = Gravity.BOTTOM;
mAdView.setLayoutParams(layoutParams2);
layout.addView(view);
layout.addView(mAdView);
// Start loading the ad.
setContentView(layout);
this will show you the ads at the bottom, GL ;)
Related
I have this animation activity for falling images. It works perfectly. What I would like to is change this, so I can call something like, startImageFallAnimation(), in another activity, and have it show over the current activity. I'd hate to have to add all this code to every activity I want to use it in. I experimented for a few hours, with no luck.
How can I accomplish this?
import com.tmp.animation.R;
public class FallAnimationActivity extends Activity {
// 100 = lots falling / 1000 = less falling
public int imageInterval = 100;
private int[] LEAVES = {
R.drawable.coin,
R.drawable.starsm,
//R.drawable.leaf_yellow,
//R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}
public void create() {
setContentView(R.layout.main);
Display display = getWindowManager().getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(FallAnimationActivity.this);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
animationLayout.width = (int) (60*mScale);
animationLayout.height = (int) (60*mScale);
startAnimation(imageView);
}
};
private class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
}
EDIT- After lots of work, this is the best I've got, but I cant solve passing context into the handler, or passing the layout into the first method.
import com.tmp.animation.R;
public class FallPop {
private static final String TAG = FallPop.class.toString();
private static final FallPop INSTANCE = new FallPop();
private int[] LEAVES = {
R.drawable.leaf_green,
R.drawable.leaf_red,
R.drawable.leaf_yellow,
R.drawable.leaf_other,
};
private Rect mDisplaySize = new Rect();
private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();
private float mScale;
private FallPop(){
}
public static FallPop getInstance() {
return INSTANCE;
}
public Context context;
public Context context2;
int count = 0;
public void doAnim(Context context){
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getRectSize(mDisplaySize);
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScale = metrics.density;
// FIX!!!
// mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);
new Timer().schedule(new ExeTimerTask(), 0, 200);
}
public void startAnimation(final ImageView aniView) {
aniView.setPivotX(aniView.getWidth()/2);
aniView.setPivotY(aniView.getHeight()/2);
long delay = new Random().nextInt(Constants.MAX_DELAY);
final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
animator.setDuration(Constants.ANIM_DURATION);
animator.setInterpolator(new AccelerateInterpolator());
animator.setStartDelay(delay);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
int angle = 50 + (int)(Math.random() * 101);
int movex = new Random().nextInt(mDisplaySize.right);
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = ((Float) (animation.getAnimatedValue())).floatValue();
aniView.setRotation(angle*value);
aniView.setTranslationX((movex-40)*value);
aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
}
});
animator.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int viewId = new Random().nextInt(LEAVES.length);
// Need some context here \/
Drawable d = ContextCompat.getDrawable(context, LEAVES[viewId]);
// Original line, also didnt work \/
//Drawable d = getResources().getDrawable(LEAVES[viewId]);
LayoutInflater inflate = LayoutInflater.from(context);
ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
imageView.setImageDrawable(d);
mRootLayout.addView(imageView);
mAllImageViews.add(imageView);
RelativeLayout.LayoutParams animationLayout = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
animationLayout.setMargins(0, (int) (-150 * mScale), 0, 0);
animationLayout.width = (int) (60 * mScale);
animationLayout.height = (int) (60 * mScale);
startAnimation(imageView);
}
};
class ExeTimerTask extends TimerTask {
#Override
public void run() {
// we don't really use the message 'what' but we have to specify something.
mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
}
}
}
Create a Java class with static method startImageFallAnimation(),where you will write all your animation code and just call the method wherever it is required
The quickest solution I can think of would be to make the target Activities extend this class and change the access level of the member variables in FallAnimationActivity to 'protected'. Depending on whether you need this in all/most Activities, I'd put the logic in a base class.
have context as a parameter in your util class
example:
public animation(Imageview imageview, Context mContext)
{
Animation slideLeft = AnimationUtils.loadAnimation(mContext, R.anim.slide_out_left);
imageview.startAnimation(slideLeft);
}
then in the activity you want to call it in do
// for activity
Utils.animation(Your image view, this)
//for fragment
Utils.animation(Your image view, getContext)
my utility class is called Utils, so you type whatever you named the class and call the method accordingly
So I'm doing an Android game for an assignment resit. This is not my first app but it is my first game. I've never been that much of an expert and quite frankly this is hard for me. I hope someone here can help.
I actually have two problems to add a score (I sincerely hope it's not too much). The thing is, I want to display it in a TextView. When the Sprite "bad" is hit, I want the score to increase by 1.
My first problem is that said TextView doesn't appear on my activity even when I'm not putting anything else than text in it. I tried to put it in LinearLayout, or change some parameters for its position, but I didn't find any other helpful thing on internet.
My second problem is for the score, which even if I can't see it, probably doesn't work. I found some helps saying to put a JPanel or JLabel but I don't think this is what I need. I tried a simple thing where I just made it an int that increases in the isHit and then displays it on the page. But it doesn't display anything, and the program took the bad habit of crashing before I can't even do anything when I have these written in the code.
I don't actually know which other page would be useful, so here is my GameView.java, if any other might be needed, please tell me.
package com.example.proprietaire.assignmentna2;
import com.example.proprietaire.assignmentna2.R;
import com.example.proprietaire.assignmentna2.Sprite;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GameView extends SurfaceView implements Runnable {
private SurfaceHolder holder;
private int x = 0, xSpeed = 1;
private Bitmap bmp;
Thread thread = null;
volatile boolean running = false;
static final long FPS = 10;
private long lastClick;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<Sprite> sprites2 = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private Bitmap bmpSmoke;
int score = 0;
public GameView(Context context) {
super(context);
thread = new Thread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
running = true;
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpSmoke = BitmapFactory.decodeResource(getResources(), R.drawable.smoke);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad));
sprites2.add(createSprite(R.drawable.good));
}
private Sprite createSprite(int resource) {
bmp = BitmapFactory.decodeResource(getResources(), resource);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
for (int i = temps.size() - 1; i>= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
for (Sprite sprite : sprites2) {
sprite.onDraw(canvas);
}
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = getHolder().lockCanvas();
synchronized (getHolder()) {
onDraw(c);
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
thread.sleep(sleepTime);
else
thread.sleep(10);
} catch (Exception e) {
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick> 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isHit(event.getX(), event.getY())) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpSmoke));
sprites.add(createSprite(R.drawable.bad));
sprites.add(createSprite(R.drawable.bad));
sprites2.add(createSprite(R.drawable.good));
score++;
break;
}
//TextView textView = (TextView)findViewById(R.id.textView);
//String s = "" + score;
//textView.setText((new Integer(score)).toString(Integer.parseInt(s)));
}
}
}
return true;
}
}
Here is GameActivity.java
package com.example.proprietaire.assignmentna2;
import android.app.Activity;
import android.os.Bundle;
public class GameActivity extends Activity {
GameView GV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GV = new GameView(this);
setContentView(GV);
}
}
The xml for the game is a simple TextView without any special thing added.
Thank you in advance.
I just checked some of my old code when I was making my own game, I made a dummy .xml file with nothing but a RelativeLayout in it. So your `GameActivity would look something like this:
private TextView tv;
private GameView gv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummyXml);
initializeGameView();
}
From this point on, you can play around with your GameView and your TextView. I will give an example of the start:
private void initializeGameView(){
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl_dummy_xml);
LinearLayout ll = new LinearLayout(this);
//Layout stuff
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.setGravity(Gravity.CENTER_HORIZONTAL);
//add more stuff, play around with whatever you want to do here
gv = new GameView();
ll.addView(gv);
tv = new TextView(this);
tv.setText(gv.getScore());
ll.addView(tv);
//Finally, don't forget to add the linear layout to the relative layout
rl.addView(ll);
}
Add a getScore() method to your GameView class or alternatively in a more elegant location :P
If you still have questions (after you've tried and tried and tried), feel free to ask ahead! =)
EDIT:
Updated code example with init of the TextView tv. If you want to update the textview you added at any point, add a method toughly similar to this one:
public void updateTextViewScore(){
tv.setText(gv.getScore());
}
I made the GameView and TextView variables global, therefore you can access them in any method you wish.
You probably want to call this method (thus update the textview) inside the game loop e.g. whenever the score changes.
Good luck! Hope this clears it up a bit.
Am new to android , and I would like place my problem in-front of you,,
I would like to capture an image between four coordinates , as below..
First of all I convert the image into bitmap and then set it as background to a relative layout. And i know these four coordinates.
Then how could I get the image inside the box and set it to another layout as background.
Guys please let me out from this logic....
finally i find the solution to my problem and i wana share it with you,
first of all, this is done based on the theory of transformation at +12 level.
Ok, My problem is solved with the help of "OpenCv for Android "
this is the code..
public class MainActivity extends Activity implements CvCameraViewListener2,OnTouchListener
{
Bitmap sourceBitmap,descBitmap,sourceBitmap1;
ImageView view,view2;
SurfaceView amSurfaceView ;
Mat mRgba;
private CameraBridgeViewBase mOpenCvCameraView;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("Yesssssssss", "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise bitmap for crop is here
Bitmap bitmap_source=BitmapFactory.decodeResource(getResources(), R.drawable.quadone);
if(bitmap_source==null)
Log.e("bitmap Null","nulllllll");
// these values should not exceed the limits of bitmap..
Log.e("Bitmap"," "+bitmap_source.getWidth()+" "+bitmap_source.getHeight());
sourceBitmap =BitmapFactory.decodeResource(getResources(), R.drawable.quadone);
sourceBitmap1 =BitmapFactory.decodeResource(getResources(), R.drawable.quadone);
descBitmap =BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
view = (ImageView) findViewById(R.id.imageView1);
view2=(ImageView) findViewById(R.id.imageView2);
view.setImageBitmap(sourceBitmap1);
view.setOnTouchListener(this);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.color_blob_detection_activity_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
Log.e("MAtt","Startttttttttmmmmmmmmmtttttttt");
sourceBitmap =bitmap_source;
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
Mat inputMat = new Mat();
Mat outputMat = new Mat();
descBitmap=sourceBitmap;
Utils.bitmapToMat(sourceBitmap, inputMat);
List<Point> src_pnt = new ArrayList<Point>();
Point p0 = new Point(0, 0);
src_pnt.add(p0);
Point p1 = new Point(10, 100);
src_pnt.add(p1);
Point p2 = new Point(100, 125);
src_pnt.add(p2);
Point p3 = new Point(90, 20);
src_pnt.add(p3);
Mat startM = Converters.vector_Point2f_to_Mat(src_pnt);
List<Point> dst_pnt = new ArrayList<Point>();
Point p4 = new Point(0.0, 0.0);
dst_pnt.add(p4);
Point p5 = new Point(0.0, sourceBitmap.getHeight());
dst_pnt.add(p5);
Point p6 = new Point(sourceBitmap.getWidth(), sourceBitmap.getHeight());
dst_pnt.add(p6);
Point p7 = new Point(sourceBitmap.getWidth(), 0);
dst_pnt.add(p7);
Mat endM = Converters.vector_Point2f_to_Mat(dst_pnt);
Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);
Size size = new Size(sourceBitmap.getWidth(), sourceBitmap.getHeight());
Scalar scalar = new Scalar(50.0);
Imgproc.warpPerspective(inputMat, outputMat, perspectiveTransform, size, Imgproc.INTER_LINEAR + Imgproc.CV_WARP_FILL_OUTLIERS, Imgproc.BORDER_DEFAULT, scalar);
Log.e("1=",""+inputMat.cols()+" "+inputMat.rows());
Log.e("outmat.."," "+outputMat.cols()+" "+outputMat.rows());
Utils.matToBitmap(outputMat, descBitmap);
view2.setImageBitmap(descBitmap);
// ram#san
}
#Override
public void onCameraViewStarted(int width, int height) {
// TODO Auto-generated method stub
Log.e("onCameraViewStarted","onCameraViewStarted");
}
#Override
public void onCameraViewStopped() {
// TODO Auto-generated method stub
Log.e("onCameraViewStopped","onCameraViewStopped");
}
#Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
// TODO Auto-generated method stub
mRgba= new Mat();
Utils.bitmapToMat(sourceBitmap, mRgba);
Utils.matToBitmap(mRgba, descBitmap);
view2.setImageBitmap(sourceBitmap);
return mRgba;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
if any one have doubts please place it here..
have a happy codding, Ram..
as for getting the image within the co-ordinates
Bitmap croppedBmp = Bitmap.createBitmap(originalBmp, startx, starty, endx, endy);
this will create a cropped bitmap like your after
This will (most probably) create an image from 4, 5, 6 etc. points that you click manually on the ImageView to obtain. This should work on more than 4 points selected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.img);
compositeImageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.drawable_android);
Bitmap bitmap2=BitmapFactory.decodeResource(getResources(), R.drawable.drawable_android_cr);
Bitmap resultingImage=Bitmap.createBitmap(320, 480, bitmap1.getConfig());
Canvas canvas = new Canvas(resultingImage);
Paint paint = new Paint();
paint.setAntiAlias(true);
Path path=new Path();
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
// textView.setText("Touch coordinates : " +String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
Log.e("X",String.valueOf(event.getX())+"");
Log.e("y",String.valueOf(event.getY())+"");
path.lineTo(String.valueOf(event.getX()), String.valueOf(event.getY()));
}
if(/*Touch count == 4 or 5 or 6 etc.*/){
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap2, 0, 0, paint);
compositeImageView.setImageBitmap(resultingImage);
return true;
}
}
});
}
I have class:
class AdmobAds
{
private static final int ADVIEW_NOT_INITIALIZED = 1;
private AdView adView;
public int InitAds(final String pub_id)
{
LoaderActivity.m_Activity.runOnUiThread(new Runnable() {
#Override
public void run() {
adView = new AdView(LoaderActivity.m_Activity, AdSize.BANNER, pub_id);
adView.loadAd(new AdRequest());
LoaderActivity.m_Activity.addContentView(adView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
});
return 0;
}
public int ShowAds()
{
if(adView!=null){
LoaderActivity.m_Activity.runOnUiThread(new Runnable() {
#Override
public void run() {
adView.setVisibility(View.VISIBLE);
}});
} else {
return ADVIEW_NOT_INITIALIZED;
}
return 0;
}
public int HideAds()
{
if(adView!=null){
LoaderActivity.m_Activity.runOnUiThread(new Runnable() {
#Override
public void run() {
adView.setVisibility(View.INVISIBLE);
}});
} else {
return ADVIEW_NOT_INITIALIZED;
}
return 0;
}
}
And i need to place AdMob banner in the identified locations ix and iy.
When I try to add Layout, in which we put a banner application falls.
Application write on Marmalade SDK, so do not have access to the XML, a little experience does not allow me to deal with the problem itself.
Here's what I used for displaying the ads at the top:-
adView = new AdView(LoaderActivity.m_Activity,AdSize.BANNER, appKeyFinal);
RelativeLayout layout = new RelativeLayout(LoaderActivity.m_Activity);
RelativeLayout.LayoutParams parentParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
RelativeLayout.LayoutParams adNinjaLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adNinjaLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
LoaderActivity.m_Activity.addContentView(layout,parentParams);
adView.loadAd(adRequest);
I hope this can help.
I wonder if I can get a way to let video run via videoview in full screen?
I searched a lot and tried many ways such as:
Apply theme in manifest:
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
but that does not force the video to be in full screen.
Apply in activity itself:
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
also does not force the video to be in full screen.
The only way force video to full screen is:
<VideoView android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent">
</VideoView>
This way it results in full screen video but it stretches the video itself (elongated video) ,
I'm not applying this improper solution to my videoview, so is there is any way to do it without stretching the video?
Video Class:
public class Video extends Activity {
private VideoView myvid;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myvid = (VideoView) findViewById(R.id.myvideoview);
myvid.setVideoURI(Uri.parse("android.resource://" + getPackageName()
+"/"+R.raw.video_1));
myvid.setMediaController(new MediaController(this));
myvid.requestFocus();
myvid.start();
}
}
main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<VideoView
android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Like this you can set the properties of the video by yourself.
Use a SurfaceView (gives you more control on the view), set it to fill_parent to match the whole screen
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<SurfaceView
android:id="#+id/surfaceViewFrame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" >
</SurfaceView>
</Linearlayout>
then on your java code get the surface view and add your media player to it
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
player = new MediaPlayer();
player.setDisplay(holder);
set on your media player a onPreparedListener and manually calculate the desired size of the video, to fill the screen in the desired proportion avoiding stretching the video!
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// Adjust the size of the video
// so it fits on the screen
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
surfaceViewFrame.setLayoutParams(lp);
if (!player.isPlaying()) {
player.start();
}
}
});
I modified this from a tutorial for video streaming that I followed some time ago, can't find it right now to reference it, if someone does please add the link to the answer!
Hope it helps!
EDIT
Ok, so, if you want the video to occupy the whole screen and you don't want it to stretch you will end up with black stripes in the sides. In the code I posted we are finding out what is bigger, the video or the phone screen and fitting it the best way we can.
There you have my complete activity, streaming a video from a link. It's 100% functional. I can't tell you how to play a video from your own device because I don't know that. I'm sure you will find it in the documentation here or here.
public class VideoPlayer extends Activity implements Callback, OnPreparedListener, OnCompletionListener,
OnClickListener {
private SurfaceView surfaceViewFrame;
private static final String TAG = "VideoPlayer";
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private ImageView pause;
private MediaPlayer player;
private Timer updateTimer;
String video_uri = "http://daily3gp.com/vids/familyguy_has_own_orbit.3gp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
pause = (ImageView) findViewById(R.id.imageViewPauseIndicator);
pause.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
pause.setVisibility(View.VISIBLE);
}
}
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setScreenOnWhilePlaying(true);
player.setDisplay(holder);
}
private void playVideo() {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(video_uri);
player.prepare();
} catch (Exception e) { // I can split the exceptions to get which error i need.
showToast("Error while playing video");
Log.i(TAG, "Error");
e.printStackTrace();
}
}
}).start();
}
private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoPlayer.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
playVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
//prepare the video
public void onPrepared(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
// Adjust the size of the video
// so it fits on the screen
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
surfaceViewFrame.setLayoutParams(lp);
if (!player.isPlaying()) {
player.start();
}
surfaceViewFrame.setClickable(true);
}
// callback when the video is over
public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
//pause and resume
public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (player != null) {
if (player.isPlaying()) {
player.pause();
pause.setVisibility(View.VISIBLE);
} else {
player.start();
pause.setVisibility(View.GONE);
}
}
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView1 = (VideoView) findViewById(R.id.videoview);
String SrcPath = "/mnt/sdcard/final.mp4";
videoView1.setVideoPath(SrcPath);
videoView1.setMediaController(new MediaController(this));
videoView1.requestFocus();
videoView1.start();
}
}
<VideoView
android:id="#+id/videoview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
</VideoView>
try this it's working for me
The current upvoted solution works, but there may be a simpler solution to the original problem. A commenter correctly pointed out that you could resize a VideoView using the same methodology without the cost of converting everything to a SurfaceView. I tested this in one of my apps and it seems to work. Just add the calculated layout parameters to the VideoView in the OnPreparedListener callback:
mInspirationalVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// mMediaPlayer = mp;
mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer mp) {
if(isPlaying = true) {
stopPosition = 0;
mp.start();
mVideoProgressTask = new VideoProgress();
mVideoProgressTask.execute();
}
}
});
// so it fits on the screen
int videoWidth = mp.getVideoWidth();
int videoHeight = mp.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
float screenWidth = mDisplayMetrics.widthPixels;
float screenHeight = mDisplayMetrics.heightPixels;
float screenProportion = (float) screenWidth / (float) screenHeight;
android.view.ViewGroup.LayoutParams lp = mInspirationalVideoView.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
mInspirationalVideoView.setLayoutParams(lp);
...
}
});
Here is my function which works for the full screen video without stretching it. It will automatically crop the sides of the video. It worked both portrait and landscape modes.
It was actually taken from the answer.
public void onPrepared(MediaPlayer mp) {
int videoWidth = mediaPlayer.getVideoWidth();
int videoHeight = mediaPlayer.getVideoHeight();
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
float scaleY = 1.0f;
float scaleX = (videoWidth * screenHeight / videoHeight) / screenWidth;
int pivotPointX = (int) (screenWidth / 2);
int pivotPointY = (int) (screenHeight / 2);
surfaceView.setScaleX(scaleX);
surfaceView.setScaleY(scaleY);
surfaceView.setPivotX(pivotPointX);
surfaceView.setPivotY(pivotPointY);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
Have you tried adjusting the underlying surface holder size? Try the code below it should adjust the surface holder to be the same width and height of the screen size. You should still have your activity be full screen without a title bar.
public class Video extends Activity {
private VideoView myvid;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myvid = (VideoView) findViewById(R.id.myvideoview);
myvid.setVideoURI(Uri.parse("android.resource://" + getPackageName()
+"/"+R.raw.video_1));
myvid.setMediaController(new MediaController(this));
myvid.requestFocus();
//Set the surface holder height to the screen dimensions
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
myvid.getHolder().setFixedSize(size.x, size.y);
myvid.start();
}
}
Well, I hope it helps FullscreenVideoView
It handles all boring code about surfaceView and fullscreen view and let you focus only in UI buttons.
And you can use the FullscreenVideoLayout if you don't want to build your custom buttons.
A SurfaceView gives u an optimized drawing surface
public class YourMovieActivity extends Activity implements SurfaceHolder.Callback {
private MediaPlayer media = null;
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
media = new MediaPlayer();
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
//...
}
}
MediaPlayer calls should be wrapped in a try{}.
#Override
public void surfaceCreated(SurfaceHolder holder) {
media.setDataSource("android.resource://" + getPackageName()
+"/"+R.raw.video_);
media.prepare();
int videoWidth = mp.getVideoWidth();
int videoHeight = mp.getVideoHeight();
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
android.view.
ViewGroup.LayoutParams layout = mSurfaceView.getLayoutParams();
layout.width = screenWidth;
layout.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);
mSurfaceView.setLayoutParams(layout);
mp.start();
}
I have solved this one by Custom VideoView:
I have added VideoView to ParentView in two ways From xml & programatically.
Add Custom class for VideoView named with FullScreenVideoView.java:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.VideoView;
public class FullScreenVideoView extends VideoView {
public FullScreenVideoView(Context context) {
super(context);
}
public FullScreenVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FullScreenVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
}
How to bind with xml:
<FrameLayout
android:id="#+id/secondMedia"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.my.package.customview.FullScreenVideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fullScreenVideoView"/>
</FrameLayout>
OR
How to add Programatically VideoView to ParentView:
FullScreenVideoView videoView = new FullScreenVideoView(getActivity());
parentLayout.addView(videoView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
Hope this will help you.