How to capture part of a ScrollView as its content is scrolling? - android

After extending the ScrollView class I was able to easily be notified of the scrolling in realtime.
Now I need to capture the content of this scrollview in a very specific part.
Let's say I want to capture the top of the screen (matching parent width and a defined height, like 100dp). But only the content of the ScrollView and not the rest, if there is anything else on the top but not as part of the ScrollView.
I tried using on the scrollview :
setDrawingCacheEnabled(true);
getDrawingCache(true);
setDrawingCacheEnabled(false);
Then I tried to crop so that I get the part I want :
Bitmap.createBitmap(complete, 0, 0, width, height);
Results are very far from what I want to achieve and performance are very very poor and at some point I would get either a SIGENV or getDrawingCache(true) tries to use a recycled bitmap...
So how can I easily capture the content in the desired area without too much performance hit ?
Note: this process must be done as I am scrolling the content, so inside ScrollView's onScrollChanged(final int x, final int y).
Thanks !

Since the problem was fun I implemented it, it seems to work fine. I guess that you are recreating a Bitmap each time that's why goes slow.
The idea is like this, you create an area in the ScrollView that you want to copy (see Rect cropRect and Bitmap screenshotBitmap), it's full width and you just need to set the height. The view automatically set a scroll listener on itself and on every scroll it will copy that area. Note that setDrawingCacheEanbled(true) is called just once when the view is instantiated, it basically tells the view that you will call getDrawingCache(), which will return the Bitmap on which the view is drawing itself. It then copy the area of interest on screenshotBitmap and that's the Bitmap that you might want to use.
ScreenshottableScrollView.java
package com.example.lelloman.screenshottablescrollview;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;
/**
* Created by lelloman on 16-2-16.
*/
public class ScreenshottableScrollView extends ScrollView implements ViewTreeObserver.OnScrollChangedListener {
public interface OnNewScreenshotListener {
void onNewScreenshot(Bitmap bitmap);
}
private Bitmap screenshotBitmap = null;
private Canvas screenshotCanvas = null;
private int screenshotHeightPx = 0;
private OnNewScreenshotListener listener = null;
private Rect cropRect;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public ScreenshottableScrollView(Context context) {
super(context);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ScreenshottableScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
setDrawingCacheEnabled(true);
getViewTreeObserver().addOnScrollChangedListener(this);
}
public void setOnNewScreenshotListener(OnNewScreenshotListener listener){
this.listener = listener;
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if(screenshotHeightPx != 0)
makeScrenshotBitmap(w,h);
}
public void setScreenshotHeightPx(int q){
screenshotHeightPx = q;
makeScrenshotBitmap(getWidth(), getHeight());
}
private void makeScrenshotBitmap(int width, int height){
if(screenshotBitmap != null) screenshotBitmap.recycle();
if(width == 0 || height == 0) return;
screenshotBitmap = Bitmap.createBitmap(width, screenshotHeightPx, Bitmap.Config.ARGB_8888);
screenshotCanvas = new Canvas(screenshotBitmap);
cropRect = new Rect(0,0,width,screenshotHeightPx);
}
#Override
public void onScrollChanged() {
if(listener == null) return;
Bitmap bitmap = getDrawingCache();
screenshotCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
screenshotCanvas.drawBitmap(bitmap,cropRect, cropRect,paint);
listener.onNewScreenshot(screenshotBitmap);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.example.lelloman.screenshottablescrollview.MainActivity">
<com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView
android:id="#+id/scrollView"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.example.lelloman.screenshottablescrollview.ScreenshottableScrollView>
<View
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#ff000000"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="100dp" />
</LinearLayout>
MainActivity.java
package com.example.lelloman.screenshottablescrollview;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StringBuilder builder = new StringBuilder();
Random random = new Random();
String AB = "abcdefghijklmnopqrstuvwxyz ";
for(int i=0;i<100;i++){
builder.append("\n\n"+Integer.toString(i)+"\n\n");
for(int j =0;j<1000;j++){
builder.append(AB.charAt(random.nextInt(AB.length())));
}
}
((TextView) findViewById(R.id.textView)).setText(builder.toString());
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
ScreenshottableScrollView scrollView = (ScreenshottableScrollView) findViewById(R.id.scrollView);
scrollView.setScreenshotHeightPx((int) (getResources().getDisplayMetrics().density * 100));
scrollView.setOnNewScreenshotListener(new ScreenshottableScrollView.OnNewScreenshotListener() {
#Override
public void onNewScreenshot(Bitmap bitmap) {
Log.d("MainActivity","onNewScreenshot");
imageView.setImageBitmap(bitmap);
}
});
}
}

Related

Android - CustomView - java.lang.IllegalStateException: Surface was not locked

I'm trying to draw a rectangle over camera2 textureview, when i run the code I see the usual camera screen with moving square , and when I Click (touch) it, app crashes with the error in topic. I also not sure I implemented the custom view correctly, Here are all the relevant parts, Would love some help (I'm not sure I have a good layout xml, I added ViewGroup code under OnCrearte, not sure i even need to touch xml)
-------CameraActivity.java:
package com.example.android.camera2video;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;
public class CameraActivity extends Activity {
private Context context;
CustomView customview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
customview = new CustomView(this);
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
viewGroup.addView(new CustomView(this));
if (null == savedInstanceState) {
getFragmentManager().beginTransaction()
.replace(R.id.container, Camera2VideoFragment.newInstance())
.commit();
}
}
}
-------CustomView.java
package com.example.android.camera2video;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CustomView extends SurfaceView {
private Paint paint;
private SurfaceHolder mHolder;
private Context context;
public CustomView(Context context) {
super(context);
mHolder = getHolder();
mHolder.setFormat(PixelFormat.TRANSPARENT);
this.context = context;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
}
public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// real work here
}
private void doAdditionalConstructorWork() {
// init variables etc.
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
invalidate();
if (mHolder.getSurface().isValid()) {
final Canvas canvas = mHolder.lockCanvas();
Log.d("touch", "touchRecieved by camera");
System.err.println("EXIT 1");
if (canvas != null) {
Log.d("touch", "touchRecieved CANVAS STILL Not Null");
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
canvas.drawColor(Color.TRANSPARENT);
canvas.drawCircle(event.getX(), event.getY(), 100, paint);
mHolder.unlockCanvasAndPost(canvas);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Canvas canvas1 = mHolder.lockCanvas();
if(canvas1 !=null){
canvas1.drawColor(0, PorterDuff.Mode.CLEAR);
mHolder.unlockCanvasAndPost(canvas1);
}
}
}, 1000);
}
mHolder.unlockCanvasAndPost(canvas);
}
}
return false;
}
}
-----fragment_camera2_video.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.android.camera2video.AutoFitTextureView
android:id="#+id/texture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_below="#id/texture"
android:background="#4285f4">
<Button
android:id="#+id/video"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/record" />
<ImageButton
android:id="#+id/info"
android:contentDescription="#string/description_info"
style="#android:style/Widget.Material.Light.Button.Borderless"
android:layout_width="4dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:padding="20dp"
android:src="#drawable/ic_action_info" />
</FrameLayout>
</RelativeLayout>
Only one thing can be drawing to a View at a time; once the SurfaceView is connected to the camera, you're not able to lock it for drawing yourself.
Your crash is probably because you're calling mHolder.unlockCanvasAndPost(canvas); outside of the null check.
If you want to draw over the cameara preview, you need a second View positioned on top of the SurfaceView.

Animate ImageView's Bitmap Position

I have an ImageView with width = 1080 and height = 1920
I have a bitmap with width = 3340 and height = 1920
I set the scale type of the imageView to MATRIX. So that the bitmap is not scaled to the imageView
imageView.setScaleType(ImageView.ScaleType.MATRIX);
I would like to animate the bitmap from left to right and vice versa.
Is it possible to be done? Any thoughts?
please create following Custom view class into your project
package com.company.xyz;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
/**
* Created by rohitp on 12/10/2015.
*/
public class CustomImageView extends View {
Bitmap bm;
int x, y;
boolean flag = true;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
try{
int src_resource = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);
bm = getDrawable(getResources(),src_resource);
}catch (Exception e){
}
}
public static Bitmap getDrawable(Resources res, int id){
return BitmapFactory.decodeResource(res, id);
}
public void setBm(Bitmap bm) {
this.bm = bm;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if(bm != null){
if(flag){
if (x < (getMeasuredWidth()-bm.getWidth())) {
x += 10;
Log.e("Custom",x+""+getMeasuredWidth());
}
else {
Log.e("Custom",x+" false");
flag = false;
}
}else{
if (x >0 ) {
x -= 10;
Log.e("Custom",x+" -");
}
else {
flag = true;
Log.e("Custom",x+" true");
}
}
canvas.drawBitmap(bm, x, y, new Paint());
}
invalidate();//calls this method again and again
}
}
create an layout xml with following
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.company.xyz.CustomImageView
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/animate_pic"
android:src="#drawable/test">
</com.company.xyz.CustomImageView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And you can also change bitmap through code at runtime
((CustomImageView) findViewById(R.id.animate_pic)).setBm(bm)
As per an example in this link http://www.sanfoundry.com/java-android-program-animante-bitmap/ you need to move the image using canvas inside onDraw(). So, follow this link, may be this will help you. And let me know for any issues.

How to Animate object in android while

Is there a way to for a Bitmap object to have a transparent background instead of solid color.. I'd like my background image (set on XML layout to show)?
sadly, none of the other question worked for me, otherwise, I wouldn't be asking... THANKS IN ADVANCE! ALSO, any tips on how to get the animation to work with XML?
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
public class Vehicle extends View{
Bitmap vehicle;
int x_axisMovement;
public Vehicle(Context context) {
super(context);
// TODO Auto-generated constructor stub
vehicle = BitmapFactory.decodeResource(getResources(), R.drawable.vehicle_bus);
x_axisMovement = 1024;
}
#Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT); // NOT WORKING
canvas.drawBitmap(vehicle, x_axisMovement, 400, null);
if(x_axisMovement > -256){
x_axisMovement -= 4;
}
else
{
x_axisMovement = 1024;
}
invalidate();
}
}
You can use it in xml and add it in a relative layout so youll have a view on top of another view
sample:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_launcher" >
<com.example.Vehicle
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Now com.example is the folder inside your src folder but you might have different folder just press ctrl+shift+o so it will automatically give you an hint to the class location.
Now your class
public class Vehicle extends View {
Bitmap vehicle;
int x_axisMovement;
public Vehicle(Context context) {
super(context);
init();
}
public Vehicle(Context context, AttributeSet s) {
super(context, s);
init();
}
public Vehicle(Context context, AttributeSet s, int style) {
super(context, s, style);
init();
}
public void init() {
vehicle = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
x_axisMovement = 1024;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT); // NOT WORKING
canvas.drawBitmap(vehicle, x_axisMovement, 400, null);
if (x_axisMovement > -256) {
x_axisMovement -= 4;
} else {
x_axisMovement = 1024;
}
invalidate();
}
}
You need to have that 3 constructor to enable the class to be used in an xml form.
now the result:
The background is the big ic_launcher and the image from your class in the small ic_launcher.

android - custom view has width and height of 0

I'm trying to create a custom view with two TextViews inside a vertical LinearLayout, but am totally confused as to how it all works.
Currently nothing is appearing as I my onDraw method isn't being called. I think this is due to the fact that my view (the LinearLayout?) has a width and height of both 0.
I think I should be overwriting my onMeasure, but after trying setMeasuredDimension(100,100) this still isn't working.
I am trying to inflate an xml inside the view and use the two TextViews in that.
An explanation would also be great so I can hopefully get my head around how this all works.
Thanks
size_button.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="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/sizeButtonSizeText"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/sizeButtonSlugText"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
SizeButton.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.nap.library.NapApplication;
import com.nap.library.R;
public class SizeButton extends LinearLayout {
private TextView mSize;
private TextView mSlug;
private String mSizeText;
private String mSlugText;
private Paint mPaint;
private boolean mSoldOut;
private Context mContext;
/*
public SizeButton(Context context) {
super(context);
setup();
}
public SizeButton(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
*/
public SizeButton(Context context, String size, String slug) {
super(context);
mContext = context;
mSizeText = size;
mSlugText = slug;
setup();
}
public void setSoldOut(){
this.mSoldOut = true;
}
public boolean isSoldOut(){
return mSoldOut;
}
public void setSizeText(String size){
mSize.setText(size);
}
public void setSlugText(String slug){
mSlug.setText(slug);
}
public void setup(){
mPaint = new Paint();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout buttonLayout = (LinearLayout) inflater.inflate(R.layout.size_button, null);
mSize = (TextView) buttonLayout.findViewById(R.id.sizeButtonSizeText);
mSize.setGravity(Gravity.CENTER);
mSize.setTextColor(Color.BLACK);
mSize.setText(mSizeText);
mSize.setTypeface(NapApplication.mPorter);
mSize.setWidth(10);
mSlug = (TextView) buttonLayout.findViewById(R.id.sizeButtonSlugText);
mSlug.setGravity(Gravity.CENTER);
mSlug.setTextColor(Color.BLACK);
mSlug.setText(mSlugText);
mSlug.setTypeface(NapApplication.mPorter);
invalidate();
requestLayout();
LinearLayout.LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mSize.setLayoutParams(layoutParams);
mSlug.setLayoutParams(layoutParams);
Log.i("button","in setup");
Log.i("button","width = "+this.getWidth()+" height = "+this.getHeight());
Log.i("button","width = "+mSize.getWidth()+" sizeheight = "+mSize.getHeight());
Log.i("button","width = "+mSlug.getWidth()+" slugheight = "+mSlug.getHeight());
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.i("button","in onMeasure");
setMeasuredDimension(100,100);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i("button","in ondraw");
}
}
ProductFragment.java - where the button is added to the fragment
for (int i = 0; i < mItem.getSizes().length; i++) {
final SizeButton sizeButton = new SizeButton(getActivity(),mItem.getSizes()[i],"hello");
// Each size button has a sku set as its tag
sizeButton.setTag(mItem.getSkus()[i]);
sizeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mItem.getSizes().length > 1) {
boolean selected = !sizeButton.isSelected();
if (selected) {
mCurrentSku = (String) v.getTag();
} else {
mCurrentSku = null;
}
}
configureButtons();
}
});
Log.e("button","Adding button to view");
mSizesWrapper.addView(sizeButton);
}
As your are extending a ViewGroup, you should override dispatchDraw(), not onDraw()

Android Custom Component not being displayed

Having a problem with Android Custom components. Trying to draw an oval shape but nothing happening.
I have this line in layout xml file
<android.project.realtimedata.DemoView android:id="#+id/demoView"
android:layout_width="fill_parent" android:layout_height="wrap_content" />
Here is the code for my custom component class.
package android.project.realtimedata;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;
public class DemoView extends View{
ShapeDrawable thisGauge = null;
public DemoView(Context context){
super(context);
init();
}
public DemoView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
private void init(){
int x = 10;
int y = 10;
int width = 300;
int height = 50;
thisGauge = new ShapeDrawable(new OvalShape());
thisGauge.getPaint().setColor(0xff74AC23);
thisGauge.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
thisGauge.draw(canvas);
}
}
I also have this line in onCreate method of Activity
demoView = (DemoView) findViewById(R.id.demoView);
Whenever I launch the application the custom component is not there.
I tried looking at it from LogCat and it definitely gets created.
What am I missing here?
Thanks in advance.
Make sure that you calling findViewById(R.id.demoView) after calling setContentView(...). To ensure that your view is being inflated, you can call Log.d("DemoView", "Created") from inside your DemoView constructor.

Categories

Resources