android ImageView is not Working - android

I want to renew ImageView whenever set pixel of Bitmap class. but ImageView is not working. I already use ui thread. what should i do?
this is my code.
public class MainActivity extends AppCompatActivity {
ImageView img;
DisplayMetrics dm;
Bitmap bit;
int x = 1, y = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.image);
bit = Bitmap.createBitmap(300, 400, RGB_565);
for(int i = 0; i < 300; i++){
for(int j = 0; j < 400; j++)
bit.setPixel(i,j, Color.WHITE);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
while(true) {
bit.setPixel(x++, y++, Color.BLACK);
img.setImageBitmap(bit);
img.invalidate();
try{
Thread.sleep(100);
}catch (Exception e){
}
}
}
});
}
}

Use postDelayed into your ImageView.post() method. Here I have done this on my machine. Plus don't use while(true) stop it when your pixels ends.
img = (ImageView) findViewById(R.id.image);
bit = Bitmap.createBitmap(300, 400, RGB_565);
for(int i = 0; i < 300; i++){
for(int j = 0; j < 400; j++)
bit.setPixel(i,j, Color.WHITE);
}
img.setImageBitmap(bit);
img.post(new Runnable() {
#Override
public void run() {
bit.setPixel(x, y, Color.BLACK);
img.setImageBitmap(bit);
if(++x < 300 && ++y < 400){
img.postDelayed(this, 100);
}
}
});

Try to update View using Handler.
img.post(new Runnable() {
#Override
public void run() {
}
});

Related

Using Handler to set Visibile/Invisibile a maker

I'm working with the google map for a project. I'm using an handler to set the marker visible o invisibile.
If the zoom of the camera is over the a number I have to set the marker invisible or if the zoom is lower than a number I have to set the marker Invisible. I'm using an ArrayList to save all the markers.
I need to create a timer that will continue to work until the application is closed
My problem is that the handler doesn't start.
Below there is my code:
final Handler handler = new Handler();
Runnable run = new Runnable() {
#Override
public void run() {
if (mMap.getCameraPosition().zoom > zoomLevel) {
for (int j = 0; j < players.size(); j++) {
Marker removeMarker = players.get(j).marker;
removeMarker.setVisible(false);
}
}else {
for (int j = 0; j < players.size(); j++) {
Marker removeMarker = players.get(j).marker;
removeMarker.setVisible(true);
}
}
handler.postDelayed(run, 1000);
}
};
this handler.postDelayed(run, 1000); needs to be outside of the runnable body
final Handler handler = new Handler();
Runnable run = new Runnable() {
#Override
public void run() {
if (mMap.getCameraPosition().zoom > zoomLevel) {
for (int j = 0; j < players.size(); j++) {
Marker removeMarker = players.get(j).marker;
removeMarker.setVisible(false);
}
}else {
for (int j = 0; j < players.size(); j++) {
Marker removeMarker = players.get(j).marker;
removeMarker.setVisible(true);
}
}
}
};
handler.postDelayed(run, 1000);

How to play a sound on android with a delay?

I'm doing a small school project of object detection by color. When the object arrives in the center of the screen, it must have a sound. So the sound does not stay uninterrupted, I tried to put a delay on it. But every time the application arrives at the point of playing the sound, it closes. I already researched here and in other forums and the solutions presented did not work.
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
static {
if(!OpenCVLoader.initDebug()){
Log.d("TAG", "OpenCV not loaded");
} else {
Log.d("TAG", "OpenCV loaded");
}
}
public void voltatela(View v) {
setContentView(R.layout.activity_main);
}
Mat imgHVS, imgThresholded;
Scalar sc1, sc2;
JavaCameraView cameraView;
int largura, altura;
public void Verde(View v) {
sc1 = new Scalar(45, 20, 10);
sc2 = new Scalar(75, 255, 255);
irTelaCamera();
}
public void Azul(View v) {
sc1 = new Scalar(80, 50, 50);
sc2 = new Scalar(100, 255, 255);
irTelaCamera();
}
public void Vermelho(View v) {
sc1 = new Scalar(110, 100, 50);
sc2 = new Scalar(130, 255, 255);
irTelaCamera();
}
public void irTelaCamera(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.telacamera);
cameraView = (JavaCameraView)findViewById(R.id.cameraview);
cameraView.setCameraIndex(0); //0 para traseira e 1 para dianteira
cameraView.setCvCameraViewListener(this);
cameraView.enableView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
}
#Override
protected void onPause() {
super.onPause();
cameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
imgHVS = new Mat(width,height, CvType.CV_16UC4);
imgThresholded = new Mat(width,height, CvType.CV_16UC4);
largura = width;
altura = height;
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Point centrotela = new Point((largura*0.5),(altura*0.5));
final MediaPlayer som = MediaPlayer.create(this, R.raw.bip);
Imgproc.medianBlur(imgHVS,imgHVS,1);
Imgproc.cvtColor(inputFrame.rgba(), imgHVS,Imgproc.COLOR_BGR2HSV);
Core.inRange(imgHVS, sc1, sc2, imgThresholded);
Imgproc.GaussianBlur(imgThresholded, imgThresholded, new Size(3, 3), 1, 1);
Mat circles = new Mat();
double dp = 1.2d;
int minRadius = 20;
int maxRadius = 0;
double param1 = 100, param2 = 20;
int desvio = (int) (minRadius*0.5);
Imgproc.HoughCircles(imgThresholded, circles, Imgproc.HOUGH_GRADIENT, dp, imgThresholded.rows()/4, 100, 20, minRadius, maxRadius);
int numCircles = (circles.rows() == 0) ? 0 : circles.cols();
for (int i = 0; i < numCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int radius = (int) circleCoordinates[2];
if((((center.x-desvio) <= centrotela.x) && ((center.x+desvio) >= centrotela.x))) {
if ((((center.y-desvio) <= centrotela.y) && ((center.y+desvio) >= centrotela.y))) {
som.start();
Imgproc.circle(imgThresholded, center, radius, new Scalar(100, 255, 255), 4);
// Play sound after 2 sec delay
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
som.stop();
}
}, 2000);
}}
}
Imgproc.circle(imgThresholded,centrotela,50, new Scalar(100,255,255),7);
Imgproc.circle(imgThresholded,centrotela,25, new Scalar(100,255,255),4);
Imgproc.circle(imgThresholded,centrotela,5, new Scalar(100,255,255),-1);
return imgThresholded;
}
}
You have to write sop.start(); instead of sop.stop() inside the handler;
Have you tried playing the sound in a different thread (AsyncTask? See example here). You would have to keep track if you have already spawned a task though, otherwise, you will end up creating too many threads playing the same sound.

RecyclerViews and AnimationDrawables - how can I put AnimationDrawables into a ViewHolder without them stopping on having another view in the window?

Basically, I have an AnimationDrawable that I generated with a helper method:
public static AnimationDrawable requestLoadingDrawable(Context originContext) {
if(panoramaLoadingLoopDrawable == null) {
panoramaLoadingLoopDrawable = new AnimationDrawable();
Bitmap src = BitmapFactory.decodeResource(originContext.getResources(), R.drawable.load360_3lines);
BitmapDrawable frameInDrawable;
//int squareInstDim = (int)(200*adapterCtx.getResources().getDisplayMetrics().density);
int horiDim = (int)(src.getWidth() / 10);
int vertDim = (int)(src.getHeight() / 3);
Bitmap frame;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 10; j++) {
frame = Bitmap.createBitmap(src, j * horiDim, i*vertDim, horiDim, vertDim);
frameInDrawable = new BitmapDrawable(originContext.getResources(), frame);
panoramaLoadingLoopDrawable.addFrame(frameInDrawable, (1000/30));
}
}
src.recycle();
}
panoramaLoadingLoopDrawable.setOneShot(false);
return panoramaLoadingLoopDrawable;
}
The panoramaLoadingLoopDrawable is private static in this helper class.
When I put it in the RecyclerView, when there's 2 items that use this AnimationDrawable in the ViewHolder, both would stop animating.
Should I make the panoramaLoadingLoopDrawable non-static or something?

How to faster renew ImageView by Bitmap

I want to renew imageView fastly. My code is that ImageView is changed every 3 colors. It operates correctly. but very slow. I want to faster operate the code. what should i do? This is my code.
public class MainActivity extends AppCompatActivity {
ImageView img;
int[] arr = new int[300];
int colorArr[] = {Color.BLACK, Color.GREEN, Color.RED};
char color = 0;
DisplayMetrics dm;
Bitmap bit;
int x = 1, y = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.image);
bit = Bitmap.createBitmap(300, 400, RGB_565);
for(int i = 0 ; i < 300; i++)
arr[i] = colorArr[color%3];
for(int i = 0; i < 300; i++){
for(int j = 0; j < 400; j++)
bit.setPixel(i,j, Color.WHITE);
}
img.post(new Runnable() {
#Override
public void run() {
bit.setPixels(arr, 0, 300, 0, y++, 300,1);
img.setImageBitmap(bit);
img.post(this);
if(y == 400){
color++;
for(int i = 0; i < 300; i++)
arr[i] = colorArr[color%3];
y = 0;
}
}
});
}
}

How to scale the images so that they should occupy the entire screen

I am developing a brick game here is the code
public class Sprite {
private static final int NO_COLUMNS = 12;
Bitmap bmp,bar,brick,scalebit;
GameView gameview;
int x,speedx=0,speedy=0;
int no_bricksperline;
private int currentFrame=0;
private int width;
private int height;
int brwidth;
int brheight;
int init=0;
float tempwidth;
String[][] bricks;
GameThread thread;
private int y;
Paint paint=new Paint();
private int barx;
private int bary;
#SuppressLint("FloatMath")
public Sprite(GameView gameview,GameThread thread,Bitmap bmp,Bitmap bar,Bitmap brick)
{
this.gameview=gameview;
this.bmp=bmp;
this.bar=bar;
this.brick=brick;
this.thread=thread;
this.no_bricksperline=gameview.getWidth()/brick.getWidth()-2;
bricks=new String[no_bricksperline][4];
brwidth=brick.getWidth();
brheight=brick.getHeight();
paint.setColor(Color.BLACK);
for (int i = 0; i < no_bricksperline; ++i)
for (int j = 0; j < 4; ++j)
bricks[i][j] = "B";
String strwidth=String.valueOf(((float)(bmp.getWidth())/NO_COLUMNS));
if(strwidth.contains("."))
{
scalebit=Bitmap.createScaledBitmap(bmp, (int)(Math.ceil(((float)bmp.getWidth())/NO_COLUMNS))*NO_COLUMNS, bmp.getHeight(), true);
}
else
{
scalebit=bmp;
}
this.width=scalebit.getWidth()/NO_COLUMNS;
this.bary=gameview.getHeight()-100;
this.height=scalebit.getHeight();
Random random=new Random();
x = random.nextInt(gameview.getWidth() - width);
y = random.nextInt(gameview.getHeight() - height)-100;
if(y<=100)
{
y=120;
}
speedx=random.nextInt(10)-5;
speedy=random.nextInt(10)-5;
}
public void update()
{
if(x>gameview.getWidth()-width-speedx || x+speedx<0)
{
speedx=-speedx;
}
if(y>gameview.getHeight()-height-speedy || y+speedy<0)
{
speedy=-speedy;
}
if(y+height >= bary-bar.getHeight()) {
if((x+width>barx-bar.getWidth()/2 && barx>x) || (x<barx+bar.getWidth()/2 && x>barx)) {
speedy=-speedy;
}
}
if(y>0 && y<=(5*brheight) && init==1)
{
if(x!=0){
int x1=x;
int y1=y;
if(x1>(no_bricksperline+1)*brwidth)
{
x1=(no_bricksperline)*brwidth;
}
if(x1<=brwidth)
{
x1=brwidth;
}
if(y1<=brheight)
{
y1=brheight;
}
if(y1>=(4*brheight) && y1<=(5*brheight))
{
y1=4*brheight;
}
int posi=(int)Math.floor(x1/brwidth)-1;
int posj=(int)Math.floor(y1/brheight)-1;
if(bricks[posi][posj]=="B")
{
bricks[posi][posj]="K";
speedy=-speedy;
}
}
}
if(y+height>bary+bar.getHeight())
{
}
x=x+speedx;
y=y+speedy;
currentFrame=++currentFrame%NO_COLUMNS;
}
#SuppressLint("DrawAllocation")
public void onDraw(Canvas canvas)
{
checkFinish();
update();
for (int i = 0; i < no_bricksperline; ++i){
for (int j = 0; j < 4; ++j) {
// ourHolder.lockCanvas();
if (bricks[i][j].contains("B"))
canvas.drawBitmap(brick, (i+1)*brick.getWidth(),(j+1)*brick.getHeight(),
null);
init=1;
}
}
int srcX=currentFrame*width;
int srcY=0;
Rect src=new Rect(srcX, srcY, srcX+width, srcY+height);
Rect dest=new Rect(x,y,x+width,y+width);
canvas.drawBitmap(scalebit,src,dest,null);
canvas.drawBitmap(bar, barx-bar.getWidth()/2, bary-bar.getHeight(),null);
}
private void checkFinish() {
int totalbricks=0;
for (int i = 0; i < no_bricksperline; ++i){
for (int j = 0; j < 4; ++j){
if(bricks[i][j] == "K"){
totalbricks++;
}
}
}
if(totalbricks==(no_bricksperline*4))
{
thread.setRunning(false);}
}
public void onTouch(MotionEvent event) {
barx= (int) event.getX();
}
}
the problem is bricks are displaying
When I use the brick image directly their are pixlated and also only 2 bricks are displaying. So I have write a logic to display min no of bricks
I have used some logic in my code
here is the code
String strwidth=String.valueOf(((float)(bmp.getWidth())/NO_COLUMNS));
if(strwidth.contains("."))
{
scalebit=Bitmap.createScaledBitmap(bmp, (int)(Math.ceil(((float)bmp.getWidth())/NO_COLUMNS))*NO_COLUMNS, bmp.getHeight(), true);
}
else
{
scalebit=bmp;
}
but there is a gap between walls and bricks. How can I make the bricks to occupy the entire screen.
use this
this.no_bricksperline=gameview.getWidth()/brick.getWidth();
instead of
this.no_bricksperline=gameview.getWidth()/brick.getWidth()-2;
If i have understood you correctly, your problem is the width of the bricks to be adjusted to fill the entire screen.
try to use this one
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
dispWidth=metrics.widthPixels;
//make the dispWidth your gameView width
use the imageview property
android:scaleType="..."

Categories

Resources