草庐IT

android - 将 ImageView 更改为黑色和白色而不是可绘制对象

coder 2023-12-19 原文

我想将 imageview 更改为黑色和白色,而不是 drawable。这样做的原因是因为用户拍了一张照片并将其显示在 ImageView 中如果您知道如何执行此操作,我将不胜感激,谢谢。

package com.example.triptych4;

import java.io.File;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {


    // label our logs "CameraApp3"
    private static String logtag = "CameraApp3";
    // tells us which camera to take a picture from
    private static int TAKE_PICTURE = 1;
    // empty variable to hold our image Uri once we store it
    private Uri imageUri;

    private Integer[] pics = { R.drawable.android, R.drawable.android3d,
          R.drawable.background3 };

    {

    ImageView imageView = (ImageView)findViewById(R.id.imageView1);

    ColorMatrix matrix = new ColorMatrix();
    matrix.setSaturation(0);

    ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
    imageView.setColorFilter(filter);

    }

    private ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Gallery gallery = (Gallery) findViewById(R.id.gallery1);
        gallery.setAdapter(new ImageAdapter(this));
        imageView = (ImageView) findViewById(R.id.imageView1);

        gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
                    long arg3) {
                Toast.makeText(getApplicationContext(), "pic:" + arg2, 
                        Toast.LENGTH_SHORT).show();
                imageView.setImageResource(pics[arg2]);

            }
        });


        // look for the button we set in the view
        ImageButton cameraButton = (ImageButton)
                findViewById(R.id.button_camera);
        // set a listener on the button
        cameraButton.setOnClickListener(cameraListener);

    }




    // set a new listener
    private OnClickListener cameraListener = new OnClickListener() {
        public void onClick(View v) {
            // open the camera and pass in the current view
            takePhoto(v);
        }
    };

    public void takePhoto(View v) {
        // tell the phone we want to use the camera
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // create a new temp file called pic.jpg in the "pictures" storage area of the phone
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
        // take the return data and store it in the temp file "pic.jpg"
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        // stor the temp photo uri so we can find it later
        imageUri = Uri.fromFile(photo);
        // start the camera
        startActivityForResult(intent, TAKE_PICTURE);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class ImageAdapter extends BaseAdapter{
        private Context context;
        int imageBackground;

        public ImageAdapter(Context context){
            this.context = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return pics.length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            ImageView imageView =new ImageView(context);
            imageView.setImageResource(pics[arg0]);
            return imageView;
        }
    } 
    // override the original activity result function
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // call the parent
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
        // if the requestCode was equal to our camera code (1) then...
        case 1:
            // if the user took a photo and selected the photo to use
            if(resultCode == Activity.RESULT_OK) {
                // get the image uri from earlier
                Uri selectedImage = imageUri;
                // notify any apps of any changes we make
                getContentResolver().notifyChange(selectedImage, null);
                // get the imageView we set in our view earlier
                ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
                // create a content resolver object which will allow us to access the image file at the uri above
                ContentResolver cr = getContentResolver();
                // create an empty bitmap object
                Bitmap bitmap;
                try {
                    // get the bitmap from the image uri using the content resolver api to get the image
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
                    // set the bitmap to the image view
                    imageButton.setImageBitmap(bitmap);
                    // notify the user
                    Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
                } catch(Exception e) {
                    // notify the user
                    Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
                    Log.e(logtag, e.toString());
                }
            }   
        }   
    }     
}

日志:

05-22 10:26:07.156: D/AndroidRuntime(24617): Shutting down VM
05-22 10:26:07.156: W/dalvikvm(24617): threadid=1: thread exiting with uncaught exception (group=0x41cac700)
05-22 10:26:07.156: E/AndroidRuntime(24617): FATAL EXCEPTION: main
05-22 10:26:07.156: E/AndroidRuntime(24617): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.triptych4/com.example.triptych4.MainActivity}: java.lang.NullPointerException
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.os.Looper.loop(Looper.java:137)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.main(ActivityThread.java:5419)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.reflect.Method.invokeNative(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.reflect.Method.invoke(Method.java:525)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at dalvik.system.NativeStart.main(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617): Caused by: java.lang.NullPointerException
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.Activity.findViewById(Activity.java:1914)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at com.example.triptych4.MainActivity.<init>(MainActivity.java:47)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.Class.newInstanceImpl(Native Method)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at java.lang.Class.newInstance(Class.java:1130)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
05-22 10:26:07.156: E/AndroidRuntime(24617):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
05-22 10:26:07.156: E/AndroidRuntime(24617):    ... 11 more

最佳答案

您可以使用 ColorMatrix 并将饱和度设置为零,从而转动 你的图像变成黑白的。然后,您将该 ColorMatrix 用作过滤器 为您的 imageView。

ImageView imageView = (ImageView)findViewById(R.id.imageView);
...

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);

ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageView.setColorFilter(filter);

关于android - 将 ImageView 更改为黑色和白色而不是可绘制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386671/

有关android - 将 ImageView 更改为黑色和白色而不是可绘制对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  7. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  8. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  9. ruby - Capistrano 3 在任务中更改 ssh_options - 2

    我尝试使用不同的ssh_options在同一阶段运行capistranov.3任务。我的production.rb说:set:stage,:productionset:user,'deploy'set:ssh_options,{user:'deploy'}通过此配置,capistrano与用户deploy连接,这对于其余的任务是正确的。但是我需要将它连接到服务器中配置良好的an_other_user以完成一项特定任务。然后我的食谱说:...taskswithoriginaluser...task:my_task_with_an_other_userdoset:user,'an_othe

  10. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

随机推荐